Flash消息在rails中出现两次

tes*_*sad 5 flash ruby-on-rails ruby-on-rails-3 twitter-bootstrap

我的Flash消息出现了两次,我的网络研究告诉我这是由于渲染和重定向显示消息.我想我需要在某个地方使用flash.now []或flash []进行排序,但我无法找到它需要去的地方

guidelines_controller.rb

def update
  @guideline = Guideline.find(params[:id])

  respond_to do |format|
    if @guideline.update_attributes(params[:guideline])
      @guideline.update_attribute(:updated_by, current_user.id)
      format.html { redirect_to @guideline, notice: 'Guideline was successfully updated.' }
      format.json { head :no_content }
    else
      format.html { render action: "show" }
      format.json { render json: @guideline.errors, status: :unprocessable_entity }
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

布局/ application.html.erb

<div class="container">

    <% flash.each do |type, message| %>

        <div class="alert <%= flash_class type %>">
            <button class="close" data-dismiss="alert">x</button>
            <%= message %>
        </div>
    <% end %>
</div>

application_helper.rb

def flash_class(type)
  case type
  when :alert
    "alert-error"
  when :notice
    "alert-success"
  else
    ""
  end
end
Run Code Online (Sandbox Code Playgroud)

guideline_controller.rb

def show
    @guideline = Guideline.find(params[:id])
    if @guideline.updated_by
     @updated = User.find(@guideline.updated_by).profile_name
   end

      if User.find(@guideline.user_id)
     @created = User.find(@guideline.user_id).profile_name
      end

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @guideline }

    end
  end
Run Code Online (Sandbox Code Playgroud)

ror*_*rra 3

您可以执行类似的操作以保存一些代码行,并仅显示一次消息:

<%- if flash.any? %>
  <%- flash.keys.each do |flash_key| %>
    <%- next if flash_key.to_s == 'timedout' %>
    <div class="alert-message <%= flash_key %>">
      <a class="close" data-dismiss="alert" href="#"> x</a>
      <%= flash.discard(flash_key) %>
    </div>
  <%- end %>
<%- end %>
Run Code Online (Sandbox Code Playgroud)

通过使用 flash.discard,您可以显示 flash 消息并避免渲染两次

  • 感谢@rorra,他煞费苦心地检查了我的代码,我们发现显示视图上显示了一条额外的闪存消息。删除了它,一切正常。 (2认同)