Rails 3: validate presence of at least one has many through association item
Side note before the answer, based on the structure of your models I would use has_and_belongs_to_many instead of using this explicit linking model since it appears the linking model doesn't add anything of value.
Either way though, the answer is the same, which is to use a custom validation. Depending on whether you go with things the way they are or simplify to a has_and_belongs_to many you'll want to validate slightly differently.
validate :has_project_disciplinesdef has_project_disciplines errors.add(:base, 'must add at least one discipline') if self.project_disciplinizations.blank?end
or with has_and_belongs_to_many
validate :has_project_disciplinesdef has_project_disciplines errors.add(:base, 'must add at least one discipline') if self.project_disciplines.blank?end
I prefer simpler approach:
class Project < ActiveRecord::Base validates :disciplines, presence: trueend
This code do absolutely the same as code by John Naegle or Alex Peachey, because of validates_presence_of
exploit blank?
method too.
You can write your own validator
class Project < ActiveRecord::Base validate :at_least_one_discipline private def at_least_one_discipline # Check that at least one exists after items have been de-selected unless disciplines.detect {|d| !d.marked_for_destruction? } errors.add(:disciplines, "must have at least one discipline") end endend