Posted over 5 years ago. Visible to the public. Repeats.

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.

  1. If you don't use options setting the inverse_of is not needed.
  2. If the inverse is wrong or missing because of some options, you need to set the inverse_of manually.

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:

Copy
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:

Rails < 4

When you have two models in a has_many, has_one or 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 has_many / belongs_to association:

Copy
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 and forum.posts[0].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.

Once an application no longer requires constant development, it needs periodic maintenance for stable and secure operation. makandra offers monthly maintenance contracts that let you focus on your business while we make sure the lights stay on.

Author of this card:

Avatar
Henning Koch
Last edit:
about 1 month ago
by Florian Leinsinger
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev