Reputation: 2020
I'm trying to validate that at least one checkbox in the form has been checked, however it's not currently working.
This is what my controller looks like:
class UserExpertise < ActiveRecord::Base
belongs_to :user
validate :atleast_one_is_checked
def atleast_one_is_checked
errors.add(:base, "Select at least one expertise") unless :gardening || :cooking || :cleaning || :washing_up
end
end
However, no error shows up when none of them are selected. Incidentally, if instead I were to remove the 'unless' portion of the code, as follows, an error shows all the time, regardless of how many or how few are selected.
def atleast_one_is_checked
errors.add(:base, "Select at least one expertise")
end
end
I can't get validation that at least one checkbox has been selected though, as the above does not seem to work. Any help would be appreciated!
Upvotes: 1
Views: 1319
Reputation: 1351
:gardening
, :cooking
, :cleaning
and :washing_up
are symbols here, they're treated by the conditional statements as true
values. Use methods related to the attributes, just:
def atleast_one_is_checked
errors.add(:base, "Select at least one expertise") unless gardening || cooking || cleaning || washing_up
end
Upvotes: 2