代码之家  ›  专栏  ›  技术社区  ›  morris menanya

正确显示Rails flash错误消息

  •  0
  • morris menanya  · 技术社区  · 2 年前

    我很难让flash[:error]消息在浏览器上正确显示,但我得到了这个 enter image description here 我需要它显示“必须存在”或“作者必须存在”的错误消息。没有额外的语法和括号。我知道它看起来很混乱,但我似乎无法解决这个问题

    这就是我的创作动作

    @policy = Policy.create(policy_params)
      
          respond_to do |format|
            if @policy.valid?
             format.html { redirect_to policy_url(@policy), notice: "Policy was successfully created." }
             format.json { render :show, status: :created, location: @policy}
            else
              format.html do
                flash[:error] = @policy.errors
                redirect_to new_policy_path
             end
            end
    

    在我看来,flash错误语法如下

    <%= flash[:error] %></h3>
    
    
    1 回复  |  直到 2 年前
        1
  •  1
  •   Knyazik01    2 年前

    您可以使用 full_messages 属性以出错:
    flash[:error] = @policy.errors.full_messages.first

    flash[:error] = @policy.errors.full_messages.to_sentence

    此外,最好使用 alert notice https://www.rubyguides.com/2019/11/rails-flash-messages/