3

控制器中有一个动作。它只能通过 ajax 以 json 格式调用。

def update
    @article = Article.find_by_id params[:id]
    respond_to do |format|
      if @article.update_attributes(params[:article])
        flash[:message] = "good"       
      else
        flash[:error] = @article.errors.full_messages.join(", ")
      end
          format.json { render :json => flash}
  end

end

页面的一部分

<% unless flash[:error].blank? %>
   <%= flash[:error] %>
<% end %>

<% unless flash[:message].blank? %>
  <%= flash[:notice] %>
<% end %>
<!-- page content goes -->

当然,页面包含调用方法的button_towith 。:remote=>trueupdate

最重要的是,它在更新后什么都没有显示。JSON 对象肯定会返回,我可以在 fireBug 中看到它。

问题是,我是否正确使用闪光灯?以及如何使用它在页面上显示消息?请不要忘记ajax。

4

3 回答 3

4

为什么你的 respond_to 块中有 if/else 语句?

def update
  @article = Article.find_by_id params[:id]
  if @article.update_attributes(params[:article])
    flash[:notice] = "Good"
  else
    flash.now[:notice] = "Bad"
    render "edit"
  end
  respond_to do |format|
    format.html {redirect_to @article}
    format.js
  end
end

然后创建update.js.erb

$("#notice").text("<%= escape_javascript(flash[:notice]) %>")
$("#notice").show()

上面的代码可能不是 100% 正确的。

对于闪存,我会有类似的东西:

<div id="notice">
  <% flash.each do |key, value| %>
    <%= content_tag(:div, value, :class => "flash #{key}") %>
  <% end %>
</div>
于 2012-08-14T10:34:51.090 回答
1

此帖子包含您需要的所有代码。它拯救了我的隐藏:

https://gist.github.com/linjunpop/3410235

这是它的一个分支,做了一些小的修改:

https://gist.github.com/timothythehuman/5506787

于 2013-06-14T02:54:20.740 回答
-1

我认为您必须绑定ajax:success回调,该回调将通过替换消息或将消息放置到 dom 来显示 Flash 消息。

于 2012-08-13T19:59:12.510 回答