Ruby on Rails: Associations May 5th, 2015

  • Associations between models make common operations simpler and easier
    class Customer < ActiveRecord::Base
     has_many :orders, dependent: :destroy
    end
     
    class Order < ActiveRecord::Base
     belongs_to :customer
    end
  • By declaring that one model belongs_to another, you instruct Rails to maintain Primary Key-Foreign Key information between instances of the two models, and you also get a number of utility methods added to your model…
    • belongs_to … sets up a one-to-one connection with another model (the belong_to model declared needs to be singular e.g. :customer)
    • has_one … sets up a one-to-one connection with another model (opposite direction from belongs_to)
    • has_many … one-to-many connection with another model, often found on the other side of a belongs to association
    • has_many :through … many-to-many connection indicating that the declaring model can be matched with zero or more instances of another model by proceeding through a third model…
      class Physician < ActiveRecord::Base
       has_many :appointments
       has_many :patients, through: :appointments
      end
    • has_one :through … one-to-one connection indicating that the declaring model can be matched with an instance of another model by proceeding through a third model
    • has_and_belongs_to_many … a direct many-to-many connection
  • belongs_to vs. has_one
    • The distinction is in where you place the foreign key (it goes on the table for the class declaring the belongs_to association)
    • Should make common sense via ownership (e.g. a user owns an account, not an account owns a user)
  • has_many :through vs. has_and_belongs_to_many
    • The simplest rule of thumb is that you should set up a has_many :through relationship if you need to work with the relationship model as an independent entity
    • If you don’t need to do anything with the relationship model, it may be simpler to set up a has_and_belongs_to_many relationship (though you’ll need to remember to create the joining table in the database)
    • You should use has_many :through if you need validations, callbacks, or extra attributes on the join model
  • Use advanced polymorphic associations when a model can belong to more than one other model (different from has_many)
  • Self joins for a single model with internal relationships (e.g. employees table with managers and subordinates)
    class Employee < ActiveRecord::Base
     has_many :subordinates, class_name: "Employee",
       foreign_key: "manager_id"
     belongs_to :manager, class_name: "Employee"
    end
  • If you create an association some time after you build the underlying model, you need to remember to create an add_column migration to provide the necessary foreign key

Resources