开发者

Render different action for ajax vs html request in rails 3

开发者 https://www.devze.com 2023-02-08 15:33 出处:网络
In rails three I have the following code for my destroy action in a photos controller def destroy @photo = Photo.find(params[:id])

In rails three I have the following code for my destroy action in a photos controller

 def destroy
      @photo = Photo.find(params[:id])
     if @photo.destroy
       flash[:notice] = t('photo.deleted')
       respon开发者_JAVA百科d_to do |format|
         if request.xhr?
           format.js
         else
           format.html {redirect_to photos_path}
         end
       end
     else
       flash[:alert] = t('.photo.error_deleting')
       if request.xhr?
         redirect_to(photos_url)
       else
         redirect_to(photo_path @photo)
       end
     end
   end

The goal is essentially to redirect to the index page if this is called from a standard link and render destroy.js if called from a remote link. This works but I was wondering if there is a cleaner way of doing this in rails 3. Possibly using the respond_with operator?

Thanks


This should work for you:

respond_to :html, :js

def destroy
  @photo = Photo.find(params[:id])
  if @photo.destroy
    flash[:notice] = t('photo.deleted')
  else
    flash[:alert] = t('.photo.error_deleting')
  end

  respond_with(@photo)
end

There is a good blog post about it here: http://ryandaigle.com/articles/2009/8/10/what-s-new-in-edge-rails-default-restful-rendering

Here's a quote from the post about the logic:

If the :html format was requested:

  • If it was a GET request, invoke render (which will display the view template for the current action)
  • If it was a POST request and the resource has validation errors, render :new (so the user can fix their errors)
  • If it was a PUT request and the resource has validation errors, render :edit (so the user can fix their errors)
  • Else, redirect to the resource location (i.e. user_url)

If another format was requested, (i.e. :xml or :json)

  • If it was a GET request, invoke the :to_format method on the resource and send that back
  • If the resource has validation errors, send back the errors in the requested format with the :unprocessable_entity status code
  • If it was a POST request, invoke the :to_format method on the resource and send that back with the :created status and the :location of the new created resource
  • Else, send back the :ok response with no body

A little more on the to_format part from the documentation:

First we try to render a template, if the template is not available, we verify if the resource responds to :to_format and display it.

There is also a Railscast about it: http://railscasts.com/episodes/224-controllers-in-rails-3

0

精彩评论

暂无评论...
验证码 换一张
取 消