Hi everyone, I’ve been reading the Active Record Associations guide and came across the section on Bi-directional Associations. The guide explains that we should define the inverse_of
option when using non-conventional foreign keys so Rails can correctly identify the bi-directional relationship between associated models.
According to Rails guide example we should define inverse_of option on has_many relation side.
class Author < ApplicationRecord
has_many :books, inverse_of: "writer"
end
class Book < ApplicationRecord
belongs_to :writer, class_name: "Author", foreign_key: "author_id"
end
This works perfectly fine, and Rails identifies the bi-directional association correctly.
However, in the API documentation for belongs_to
, I found a note suggesting that it’s also a good idea to specify inverse_of
on the belongs_to
side when using the foreign_key
option.
That confused me little bit and because of this, I’ve started adding inverse_of
on the belongs_to
side whenever I use the foreign_key
option, like so:
class Author < ApplicationRecord
has_many :books, inverse_of: "writer"
end
class Book < ApplicationRecord
belongs_to :writer, class_name: "Author", foreign_key: "author_id", inverse_of: :books
end
So far, this has worked well for me. Do we need define it like that are should I just follow Rails Guides?