How To: Create a has_two relationship in rails

Occasionally you need to create a has_many relationship that is limited to just two or more child instances.

For example; we want users to supply their home and work addresses. We can achieve this by naming our associations and supplying class names.

class User  
  has_one :home_address, class_name: 'Address', foreign_key: 'home_address_id'
  has_one :work_address, class_name: 'Address', foreign_key: 'work_address_id'

An alternative use case could be; we want Groups to contain a maximum of 4 Friends

class Group  
  has_many :friends
  validates_length_of :friends, maximum: 4

Joe Woodward

Read more posts by this author.