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

Updated . Posted . Visible to the public.

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).

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
Profile picture of Dominik Schöler
Dominik Schöler
Last edit
Dominik Schöler
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2013-03-26 19:00)