简体   繁体   English

respond_with & Flash 通知

[英]respond_with & Flash Notice

I have the following in one of my controllers:我的一个控制器中有以下内容:

def create

  photo.user = current_user if current_user
  flash[:notice] = "The photos was saved" if photo.save
  respond_with photo, :location => photo_path(photo)

end

This code works with one exception.此代码有一个例外。 If I access this action w/ some kind of AJAX, and then visit another page, the flash notice will get displayed.如果我使用某种 AJAX 访问此操作,然后访问另一个页面,则会显示 flash 通知。 How can I only display the flash notice when responding with:html?如何在响应时只显示 flash 通知:html? I thought maybe you could pass a:notice => "my flash" to respond_with but no luck.我想也许你可以将 a:notice => "my flash" 传递给respond_with但没有运气。

You can put condition like:您可以将条件设置为:

flash[:notice] = "The photos was saved" if photo.save && !request.xhr?

Also, if some day you will decide use generated notice when responding to AJAX request, you can use flash.discard to clear flash.此外,如果有一天您决定在响应 AJAX 请求时使用生成的通知,您可以使用flash.discard清除 flash。

Use as below:使用如下:

respond_to do |format|
  format.html { redirect_to photo_path(photo), :notice => 'The photos was saved') }
  format.xml  { render :xml => photo, :status => :created}
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM