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 web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
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)