Read more

Rails: How to use a n:m association as 1:n association

Dominik Schöler
March 26, 2013Software engineer at makandra GmbH

Sometimes you might want to limit the number of associated records in a has_many association, but cannot add a foreign key to the other model (using belongs_to).

Illustration book lover

Growing Rails Applications in Practice

Check out our e-book. Learn to structure large Ruby on Rails codebases with the tools you already know and love.

  • Introduce design conventions for controllers and user-facing models
  • Create a system for growth
  • Build applications to last
Read more Show archive.org snapshot

There are many Show archive.org snapshot takes Show archive.org snapshot on limiting the number of associated records in has_many associations, but none feels smooth.

However, when your limit is 1, there is an elegant solution: Simply add validates_uniqueness_of :association_id to your join model. In the following example, a project may have only one feedback contact.

class FeedbackContact < ActiveRecord::Base
  has_many :projects
  has_many :feedback_contacts, :class_name => 'User'
  validates_uniqueness_of :project_id
end
Posted by Dominik Schöler to makandra dev (2013-03-26 20:00)