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.

1

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.