rails 4 When is "inverse_of" required?

1.6k views Asked by At

I am developing a web app using rails 4 for the first time. I am making all of my model associations bidirectional and using inverse_of wherever it is allowed.

From reading the documentation, I've developed the impression that this is probably the best practice, but that's never really spelled out clearly anywhere.

I'd appreciate any general advice in this regard from experienced rails developers. I hope the question is not too vague to have value here.

Thanks!

Update: In addition to non-standard names, there appear to be two main additional cases where explicitly setting inverse_of is needed:

  1. for INVALID_AUTOMATIC_INVERSE_OPTIONS ( http://www.rubydoc.info/docs/rails/ActiveRecord/Reflection/AssociationReflection )
  2. if you're accepting nested attributes - This is because the parent object is not saved yet and thus does not have an id. See http://viget.com/extend/exploring-the-inverse-of-option-on-rails-model-associations
2

There are 2 answers

4
Brad Werth On BEST ANSWER

It is typically desirable to have inverses set up. The good news is that this is handled automatically in most cases. You usually only need to explicitly set the inverses for associations with non-standard names. You can find out a lot more in the official documentation.

0
OuttaSpaceTime On

This card does a pretty good job of listing some cases were it inverse_of is still required and also explains some of the background.