[英]Rails 4 - Remove attribute name from error message for associated model presence
I have two models user_item
and user_item_images
. 我有两个模型user_item
和user_item_images
。
user_item.rb 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 user_item_images.rb
belongs_to :user_item
I have a nested form with only one user_item_image
field which is :picture
. 我有一个只有一个user_item_image
字段为: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. 我不知道如何编辑en.yml文件,因为错误是由于存在另一个模型而不是模型的属性。
I looked here but the answer is too broad and I think I need a custom validation. 我在这里看过,但是答案太宽泛了,我认为我需要自定义验证。
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
For that, in your user_item_images model you need: validates :picture, presence: true
You may also want to look into whether you have data modeling issues to resolve. 为此,在user_item_images模型中,您需要: validates :picture, presence: true
您可能还想研究是否存在要解决的数据建模问题。 Regardless, your current validation only validates that the association exists. 无论如何,您当前的验证仅验证关联的存在。 So, when you submit an user_item_images form with an empty picture field the validation that fails is the one in your user_item model. 因此,当您提交带有空白图片字段的user_item_images表单时,失败的验证就是user_item模型中的验证。 Rather than attempt to change the content of association presence validation error message, add a validation for the picture column in the user_item_images. 与其尝试更改关联状态验证错误消息的内容,不如对user_item_images中的picture列添加验证。 That way if picture is empty, it will raise 'You must include a picture'. 这样,如果图片为空,则会显示“您必须包含图片”。
I'll also comment that having the presence validation :user_item_images on the user_item model shouldn't be necessary and likely indicates a larger data modelling issue that you need to resolve. 我还将评论说,不必在user_item模型上进行状态验证:user_item_images,并且可能表明您需要解决更大的数据建模问题。
There's no need to write extra code. 无需编写额外的代码。 You should use Rails' built in I18n to customise ActiveRecord error messages. 您应该使用内置于I18n的Rails来自定义ActiveRecord错误消息。
Inside config/locales/en.yml
内部config/locales/en.yml
en:
activerecord:
errors:
models:
user_item:
attributes:
user_item_images:
presence: "You must include a picture"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.