class UsersController < ApplicationController::Base def index @users = User.all respond_to do |format| format.html format.xml { render :xml => @users } format.json { render :json => @users } end end def create @user = User.create(params[:user]) respond_to do |format| format.html { redirect_to users_url } format.xml { render :xml => @user } format.json { render :json => @user } end end end
我们经常看到类似上面的代码,现在,我们可以使用respond_with实现同样的功能。
class UsersController < ApplicationController::Base respond_to :html, :xml, :json def index respond_with(@users = User.all) end def create @user = User.create(params[:user]) respond_with(@user, :location => users_url) end end
你也可以给respond_with加上一些参数,例如:status或者:head等等。
class UsersController < ApplicationController::Base respond_to :html, :xml, :json def index respond_with(@users = User.all, :status => :ok) end end
respond_with也支持block:
class UsersController < ApplicationController::Base respond_to :html, :xml, :json # Override html format since we want to redirect to a different page, # not just serve back the new resource def create @user = User.create(params[:user]) respond_with(@user) do |format| format.html { redirect_to users_path } end end end
最后来看一下:except、:only、:any的用法。
class UsersController < ApplicationController::Base respond_to :html, :only => :index respond_to :xml, :json, :except => :show ... end
class UsersController < ApplicationController::Base def index @users = User.all respond_to do |format| format.html format.any(:xml, :json) { render request.format.to_sym => @users } end end end