How to Create an Association Between Two Rails Models

Rails: How to multiple associations between two models

I see what you are trying to achieve.

First thing first, remove foreign_key: true in your CreateReviews migration because it has no effect, you might want to index those two columns by replacing it with index: true.

Then in your User model have two different has_many associations eg

class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable

has_many :client_reviews, foreign_key: "client_id", class_name: 'Review'
has_many :seller_reviews, foreign_key: "seller_id", class_name: 'Review'
end

Why two different associations? well because when you have two same associations it will always use the last association hence overriding the first one.

You might want to try it in your console and see the output, for your case if you inspect the query you will see that it is using seller_id column to find reviews if you try something like.

user = User.first
p user.reviews.to_sql

Now refactor your Review model to have something like this

class Review < ApplicationRecord
belongs_to :client, foreign_key: :client_id, class_name: 'User'
belongs_to :seller, foreign_key: :seller_id, class_name: 'User'
end

Now you can create client_reviews and seller_reviews and query each one

seller = User.create(name: 'Seller 1)
client = User.create(name: 'Client 1')

seller.seller_reviews.create(description: 'I like your product', client: client)

review = Review.first
p review.client
p review.seller

Hope it helps give the picture of what you can do.

How to create an association between two rails models

i bet, that u forget something like

def create
@journal_entry = @user.journal_entries.build(params[:journal_entry])
# @journal_entry = current_user.journal_entries.build(params[:journal_entry])
if @journal_entry.save
..

Having different associations between two models Rails

You could try either a has_many through: or a has_and_belongs_to_many relationship. Personally, I think I would use a HABTM for this, but the advantage of a HM Through is that there is an intermediate model, which can be used for additional information (such as whether an "attendee" is going or merely interested, etc): http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association

As for having multiple different associations between the same two models, you can name the association anything you like but specify the class_name of the model you are pointing to: http://guides.rubyonrails.org/association_basics.html#has-and-belongs-to-many-association-reference

For example:

class Article < ActiveRecord::Base
belongs_to :user
has_and_belongs_to_many :attendees, class_name: "User", join_table: "articles_attendees", foreign_key: "attended_event_id", association_foreign_key: "attendee_id"
...
end

And for your User model:

class User < ActiveRecord::Base
has_many :articles
has_and_belongs_to_many :attended_events, class_name: "Article", join_table: "articles_attendees", foreign_key: "attendee_id", association_foreign_key: "attended_event_id"
...
end

That way you're able to name your association whatever you like, just be sure to keep your singulars singular and your plurals plural, and generally everything readable. class_name should be the name of the model to which you are defining the relationship. foreign_key is the database column name containing the ID of the models in which the relationship is defined. For example, in your User model, foreign_key should be the user ID. The association_foreign_key is the column containing the ID of the model to which you are linking.

Also don't forget to create your migration. Something like this example:

class CreateArticlesAttendees < ActiveRecord::Migration
def self.up
create_table :articles_attendees, :id => false do |t|
t.references :attended_event
t.references :attendee
end
add_index :articles_attendees, [:attended_event_id, :attendee_id]
add_index :articles_attendees, :attendee_id
end

def self.down
drop_table :articles_attendees
end
end

Rails - Creating a belongs_to association between models prevents me from editing the model

Use:

belongs_to :moderator, class_name: "User", optional: true

In rails 5, belongs_to enforces existence of the associated record by default. You need to use optional: true in order to allow moderator_id to be nil.

Rails: Association between models

You should look up how to create a has_many/belongs_to association:

Sample Image

To get what you want, you'd use the following:

#app/models/order.rb
class Order < ActiveRecord::Base
has_many :sales
end

#app/models/sale.rb
class Sale < ActiveRecord::Base
belongs_to :order
end

You'll need to set the foreign_key of the Sale model, so that each time you invoke a @sale object, it will be associated to an @order:

$ rails g migration AddForeignKeyToSales

#db/migrate/add_foreign_key_to_sales________.rb
class AddForeignKeyToSales < ActiveRecord::Migration
def change
change_table :sales do |t|
t.references :order, after: :id
end
end
end

$ rake db:migrate

This will set the sale table to include the order_id foreign key, which you can then use with the following controller setup:

#config/routes.rb
resources :orders do
resources :sales #-> url.com/orders/:order_id/sales/new
end

#app/controllers/sales_controller.rb
class SalesController < ApplicationController
def new
@order = Order.find params[:order_id]
@sale = @order.sales.new
end

def create
@order = Order.find params[:order_id]
@sale = @order.sales.new order_params
@sale.save
end
end

How create associations between two models if one has two ID's from another

Something like this should work

class Team < ActiveRecord::Base
has_many :games
end

class Game< ActiveRecord::Base
belongs_to :hometeam, class_name: "Team", foreign_key: :hometeam_id
belongs_to :awayteam, class_name: "Team", foreign_key: :awayteam_id
end

How to create a one to many relation between models in Ruby on Rails?

Looks like you want to use a many-to-many association between students and courses. There are a number of ways to achieve this. I would go with the has_many :though option described here, in which you add an additional model called StudentCourse.

So in your scenario, you would:

  1. generate this StudenCourse model with rails generate model StudentCourse student:references model:references

  2. add the following to your Student model

    class Student
...
has_many :student_courses
has_many :courses, through: student_courses
...
end

  1. add the following to your Course model
    class Course
...
has_many :student_courses
has_many :students, through: student_courses
...
end

  1. run migrations with rake db:migrate
  2. now you can start adding students to courses and vice versa. For example:
    Student.last.courses << Course.last
Course.first.students << Student.first

and in your controllers, you can simply call student.courses to see courses that are associated with a given student, or course.students to view students taking a specific course.

notice how both Course and Student models will are now associated with each other using has_many: ..., through: :student_courses.

Another benefit of using this type of many-to-many association is flexibility. For instance, you might want to start recording whether students have dropped specific courses. You can do so by simply adding a dropped_at column to this new student_courses table.

EDIT

adding a few more detailed examples of how to use this new association:

as mentioned, you can append courses to students and vice versa via rails console. For instance, a student with id of 1 wants to enroll into a course with id of 2:

Student.find(1).courses << Course.find(2)

similarly, you can just add students to courses like so:

Course.find(2).students << Student.find(1)

under the hood, both of these associations would be creating a new instance of the StudentCourse class we added. So a third option of creating this association would be:

StudentCourse.create(student: Student.find(1), course: Course.find(2))


Related Topics



Leave a reply



Submit