为什么这会显示两个Flash消息但另一个?

时间:2013-10-31 15:47:45

标签: ruby-on-rails ruby-on-rails-3

这是视图

<%= '<br /><br />' if flash %>
<% flash.each do |name, msg| %>
  <div class="alert alert-<%= name == :notice ? "success" : name.to_s %>">
    <a class="close" data-dismiss="alert">&#215;</a>
    <%= content_tag :div, msg.html_safe, :id => "flash_#{name}" if msg.is_a?(String) %>
  </div>
<% end %>

<%= yield %>

以下代码显示删除记录后屏幕顶部只有一条Flash消息(“已删除”)。那就是我想要的。

def update

    if params[:destroy]

        if current_user.id == @code.user_id
            @code.destroy
            flash[:notice] = "Deleted"
        else
            flash[:notice] = "You don't have permission to edit"
        end

        respond_to do |format|
            format.html { redirect_to community_codes_url }
            format.json { head :no_content }
        end

    else

        respond_to do |format|
            if @code.update_attributes(params[:code])
                format.html { redirect_to community_code_path(@community.community_name, @code), notice: 'Updated' }
                format.json { head :no_content }
            else
                format.html { render action: "edit" }
                format.json { render json: @code.errors, status: :unprocessable_entity }
            end
        end

    end

end

但是下面的代码搞乱了这个规则,我完全糊涂了:(

如果我创建新记录,它应该只显示一个像前一个一样的flash消息。然后它有推文按钮。

此Flash不仅包含字符串,还包含Flash消息中的htmljavascript
我认为是否会有2条Flash消息并不重要:(

如何只显示一条Flash消息?

def create      

    @code = @community.codes.build (params[:code]) 
    @code.user_id = current_user.id

    respond_to do |format|
        if @code.save       
            tag_strings = @community.tags.join(", ") + "," if @community.tags
            flash[:notice] = '<a href="https://twitter.com/share" class="twitter-share-button" data-lang="en" data-hashtags="' + tag_strings + 'tags here!">Tweet</a><script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>You can tweet if you click this button'

            format.html { redirect_to community_code_path(@community.community_name, @code) }
            format.json { render json: [@community, @code], status: :created, location: @code }
        else
            format.html { render action: "new" }
            format.json { render json: @code.errors, status: :unprocessable_entity }
        end
    end
end

1 个答案:

答案 0 :(得分:1)

在只显示一条消息的那个消息中,您正在写入notice哈希的flash密钥,然后再次写入相同的密钥从而覆盖它。在显示两条消息的消息中,您将一次写入notice密钥,一次写入error密钥,从而产生两个密钥。然后,闪光机制显示两者。根据您使用的闪光显示机制,它们可能会以不同的颜色显示,因为它们是两个不同的“级别”问题。

如果您只想显示一个,您可以继续写入flash哈希的相同密钥。