繁体   English   中英

Rails上的自定义错误消息未显示-默认显示“ is invalid”

[英]Custom error messages on Rails not showing up - default “is invalid” showing instead

在我的模型中,我有一个简单的验证,如下所示:

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

控制器将错误消息添加到闪存中,如下所示:

  if !@post.save
     content = "Something went wrong - "
     @post.errors.full_messages.each { |msg| content += "#{msg} : " }
     flash[:error] = content
  end

我在ApplicationHelper模块中使用此帮助器功能显示错误消息:

  def flash_display
    response = ""
    flash.each do |name, msg|
      response = response + content_tag(:div, msg, :id => "flash_#{name}")
    end
    flash.discard
    response
  end

我像这样通过js插入消息:

// add the flash message
$('#flash').html("<%= escape_javascript raw(flash_display) %>");

但是我无法终生理解Rails为什么拒绝显示我的自定义错误消息:“您最多只能有3个标签”。 而是显示了相当冷淡的不人道消息:“标签无效:”。

我在做错人吗? 救命!

编辑:调试显示了更多信息,希望可以缩小我的问题。

 @post.errors.full_messages 

这仅包含我的每个标签的“无效”消息。 我想这意味着我在模型上添加的消息显然没有被拾取(或存储在错误的位置)

似乎您应该使用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

如果您不重定向,则不应使用闪光灯。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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