Rails: How to use a n:m association as 1:n association
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