简体   繁体   中英

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. How can I only display the flash notice when responding with:html? I thought maybe you could pass a:notice => "my flash" to respond_with but no luck.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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