簡體   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