Andrew N
Andrew N

Reputation: 73

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:

Author db schema:

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?

Upvotes: 6

Views: 3707

Answers (1)

Wayne Conrad
Wayne Conrad

Reputation: 107959

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

Upvotes: 9

Related Questions