Question: Using foreign_key in rails associations has_many

Question

Using foreign_key in rails associations has_many

Answers 1
Added at 2016-12-16 12:12
Tags
Question

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?

Answers to

Using foreign_key in rails associations has_many

nr: #1 dodano: 2016-12-16 12:12

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

Source Show
◀ Wstecz