0

I have a an 'items' model with two attributes - 'lunch' and 'dinner' which are boolean values. In my view to add a new item, there is a checkbox for lunch and dinner so the user can select which type of item it is. I have the validation below to ensure at least one of these two checkboxes is selected.

validates :lunch, presence: { if: -> { dinner.blank? } }
validates :dinner, presence: { if: -> { lunch.blank? } }

Right now, if neither is checked the error message says:

"Lunch can't be blank" "Dinner can't be blank"

I am trying to customize the message to something like "you must select a a meal"

I found pages on error messages but I can't figure out how to make it work with the kind of validation I have above.

James
  • 11
  • 3
  • Possible duplicate of [Fully custom validation error message with Rails](https://stackoverflow.com/questions/808547/fully-custom-validation-error-message-with-rails) – Arman H Oct 07 '17 at 00:11

1 Answers1

1

Since you need to check both columns at the same time and provide a custom error message, you need to create your own validation in your model:

validate :has_one_meal


def has_one_meal
  errors[:base] << "You must select at least one meal" unless (lunch || dinner)
end
EJAg
  • 3,210
  • 2
  • 14
  • 22