Rails: When to use :inverse_of in has_many, has_one or belongs_to associations
Rails >= 4
Starting from Rails 4 the
inverse_of is tried to be determined automatically.
- If you don't use options setting the
inverse_ofis not needed.
- If the inverse is wrong or missing because of some options, you need to set the
Our recommendation is to always set inverse of if you use any option. Still you can find out if the
inverse_of is set correctly:
Forum.reflect_on_association(:posts).has_inverse? # => false # missing and needs to be set manually Forum.reflect_on_association(:posts).has_inverse? # => :forum # looks good
Below there are some known options where a automatically determination of the
inverse is not working:
:foreign_key: See the Ruby On Rails Guide and the
INVALID_AUTOMATIC_INVERSE_OPTIONSconstant for each Rails version respectively.
:as: Association to polymorphic model does not determine inverse_of automatically.
Rails < 4
When you have two models in a
belongs_to association, you should always use the
:inverse_of option in Rails < 4 to tell ActiveRecord that they're two sides of the same association.
Example with a
class Forum < ActiveRecord::Base has_many :posts, :inverse_of => :forum end class Post < ActiveRecord::Base belongs_to :forum, :inverse_of => :posts end
By setting this option, Rails can optimize object loading so
forum.posts.forum will reference the same object in memory, instead of loading another copy of the same record. This will save you countless headaches.
Please read this great section about bi-directional associations from the Rails API for details.