ruby-on-railsvalidationactiverecordrails-i18n

Rails 4 - Remove attribute name from error message for associated model presence


I have two models user_item and user_item_images.

user_item.rb

has_many :user_item_images, dependent: :destroy
validates :user_item_images, presence: { message: "You must include a picture" }

user_item_images.rb

belongs_to :user_item

I have a nested form with only one user_item_image field which is :picture. When I submit an empty form I get this message

User item images You must include a picture

How do I make it so that the message instead says

You must include a picture

I don't know how to edit the en.yml file because the error is on the presence of another model and not an attribute of a model.

I looked here but the answer is too broad and I think I need a custom validation.


Solution

  • Create a custom validation instead:

    has_many :user_item_images, dependent: :destroy
    validate :has_a_picture
    
    private
    
    def has_a_picture
      errors.add(:base, 'You must include a picture') if user_item_images.none?
    end