简体   繁体   中英

Rails: Customizing error message for validation

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 aa 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM