respond_to do |format|
format.html
format.xml { render :xml => @mah_blogz }
end
respond_to do |format|
format.js
end
What's this respond_to
, format.html
, format.xml
and format.js
? What's their purpose and how do they work?
Here's the link to the documentation
Its a way of responding to the client based on what they are asking for, if the client asks for HTML, Rails will send back HTML to the client, if they ask for XML then XML.
Say you are doing this:
class UsersController < ApplicationController
def create
#
#your code
#
respond_to do |format|
format.xml {render :xml => xxx}
format.json {render :json => xxx}
format.html {render xxx}
end
end
def edit
#
#your code
#
respond_to do |format|
format.xml {render :xml => xxx}
format.json {render :json => xxx}
format.html {render xxx}
end
end
end
rather do:
class UsersController < ApplicationController
respond_to :xml, :json, :html
def create
#
#your code
#
respond_with xxx
end
def edit
#
#your code
#
respond_with xxx
end
end
and thats how you keep the code DRY (Dont Repeat Yourself)
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.