8

フラッシュ メッセージが 2 回表示されます。Web 調査によると、これはメッセージを表示するレンダリングとリダイレクトが原因であることがわかりました。これをソートするには、どこかで flash.now[] または flash[] を使用する必要があると思いますが、どこに移動する必要があるかわかりません

ガイドライン_コントローラー.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

レイアウト/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

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
4

3 に答える 3

2

コードの行数を節約し、メッセージを 1 回だけ表示するために、次のようにすることができます。

<%- 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 %>

flash.discard を使用すると、2 回レンダリングされないようにフラッシュ メッセージを表示できます。

于 2013-03-04T01:31:31.557 に答える