Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using foreign_key in rails associations has_many

Could somebody explain me is my code correct.

I'm trying to get foreign_key option in rails associations.

I have 2 models: Book and Author

Book db schema:

  • name
  • user_id

Author db schema:

  • name

My models:

class Author < ApplicationRecord
  has_many :books, foreign_key: :user_id
end

class Book < ApplicationRecord
  belongs_to :author, foreign_key: :user_id
end

Here I don't understand why we should define foreign_key in both models. Is it necessarily?

like image 947
Andrew N Avatar asked Dec 16 '16 11:12

Andrew N


People also ask

How is polymorphic association set up in Rails?

The basic structure of a polymorphic association (PA)sets up 2 columns in the comment table. (This is different from a typical one-to-many association, where we'd only need one column that references the id's of the model it belongs to). For a PA, the first column we need to create is for the selected model.

What is the difference between Has_one and Belongs_to?

They essentially do the same thing, the only difference is what side of the relationship you are on. If a User has a Profile , then in the User class you'd have has_one :profile and in the Profile class you'd have belongs_to :user . To determine who "has" the other object, look at where the foreign key is.


1 Answers

If you have used the table and column names that Rails expects, then you do not need to explicitly define the foreign_key. In your case, if the foreign key column was named author_id, then you could get by quite simply:

class Author < ApplicationRecord
  has_many :books
end

class Book < ApplicationRecord
  belongs_to :author
end

However, in your case, the foreign key column is not named according to what Rails expects, so you have needed to explicitly define the foreign key column name. That's fine, but it does make a little more work for you.

In cases where you have explicitly defined the foreign key, you should define it for both associations. Your has_many association will not work without it.

In addition, you should define the inverse association:

class Author < ApplicationRecord
  has_many :books, foreign_key: :user_id, inverse_of: :author
end

class Book < ApplicationRecord
  belongs_to :author, foreign_key: :user_id, inverse_of: :books
end

Defining the inverse_of can cause ActiveRecord to make fewer queries, and gets rid of a few surprise behaviors. For an explanation of inverse_of, see Exploring the :inverse_of Option on Rails Model Associations by Ryan Stenberg

like image 144
Wayne Conrad Avatar answered Sep 17 '22 03:09

Wayne Conrad