[英]Custom error messages on Rails not showing up - default “is invalid” showing instead
In my model, I have a simple validation like so: 在我的模型中,我有一个简单的验证,如下所示:
class Post
validate :max_tag_limit, if: :tags
private
def max_tag_limit
errors[:tags] << "You can only have maximum of 3 tags") if tags.count > 3
end
end
The controller adds the error messages to flash like so: 控制器将错误消息添加到闪存中,如下所示:
if !@post.save
content = "Something went wrong - "
@post.errors.full_messages.each { |msg| content += "#{msg} : " }
flash[:error] = content
end
I display my error messages using this helper function in my ApplicationHelper module: 我在ApplicationHelper模块中使用此帮助器功能显示错误消息:
def flash_display
response = ""
flash.each do |name, msg|
response = response + content_tag(:div, msg, :id => "flash_#{name}")
end
flash.discard
response
end
I insert the message through js like so: 我像这样通过js插入消息:
// add the flash message
$('#flash').html("<%= escape_javascript raw(flash_display) %>");
But i cannot for the life of me understand why Rails refuses to show my custom error message: "You can only have maximum of 3 tags". 但是我无法终生理解Rails为什么拒绝显示我的自定义错误消息:“您最多只能有3个标签”。 Instead it shows the rather cold inhuman message: "Tags is invalid :". 而是显示了相当冷淡的不人道消息:“标签无效:”。
What am i doing wrong people? 我在做错人吗? Help! 救命!
EDIT: Debugging reveals some more info, which should hopefully narrow my question. 编辑:调试显示了更多信息,希望可以缩小我的问题。
@post.errors.full_messages
This contains only the "is invalid" message for each of my tags. 这仅包含我的每个标签的“无效”消息。 I guess this means the messages i'm adding at the model, is clearly not being picked up (or is stored in the wrong location) 我想这意味着我在模型上添加的消息显然没有被拾取(或存储在错误的位置)
Seems you should use errors[:base]
instead of errors[:tags]
: 似乎您应该使用errors[:base]
而不是errors[:tags]
:
class Post
validate :max_tag_limit, if: :tags
private
def max_tag_limit
errors[:base] << "You can only have maximum of 3 tags" if tags.count > 3
end
end
And you should not be using the flash if you're not redirecting. 如果您不重定向,则不应使用闪光灯。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.