Search code examples
ruby-on-railsactiverecord

Is it valid practice to intentionally omit association definition with Rails ActiveRecord?


While been working on Ruby on Rails application, I was suggested to omit ActiveRecord association intensionally by my coworker for it's defines unnecessary methods.

Example,

class Person < ActiveRecord::Base
  has_many :pets
end

class Pet < ActiveRecord::Base
  # belongs_to :person <- Omit belongs_to association, for this is not used in anywhere.
end

I'm confused by this advice, because it's suggested to define model associations completely on most resources which describes ActiveRecord association. So, I'd like to ask the practice omitting association like this is valid or not.


Solution

  • According to the Bi-directional Associations from Rails Guide, if you specify relation in both models:

    Active Record will attempt to automatically identify that these two models share a bi-directional association based on the association name. This information allows Active Record to:

    • Prevent needless queries for already-loaded data.
    • Prevent inconsistent data.
    • Autosave associations in more cases.
    • Validate the presence and absence of associations in more cases.

    Therefore it is considered as best practice. Also you will be able to use methods and options provided by belongs_to.

    However, it is not necessary to add them both, you can use one sided relation if it meets your needs.