I an new in ruby and rails.
Following the guide in ror document,I create the blog application.
Howver when I see the code generated,I found that I can not understand them,for exmpale:
def show
@post = Post.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @post }
end
end
The repond_to is a method(isn't it?),and the following block is the argument?
However what does the code inner the block mean?
format.html # show.html.erb
format.json { render json: @post }
Is the format.html is the name of the method or something else?
ANd how about the { render json: @post }
>?
The respond_to
method helps you to deliver the content in the format requested. For example, if you call /posts/1.json
, the response would be a JSON file. If it's /posts/1.html
, the response would be an HTML page. The default when no extension is provided is to render HTML.
The format.json
method tells Rails what to do when requested that extension, like for example, if for every JSON request you would like to increase a counter, but not for HTML requests, you could do:
format.json {
counter = counter + 1
render json: @post
}
If you don't provide a block to the format.json
method, Rails automagically will try and look inside views/posts/
for a show.json.erb
file, and render that. In the method you provided, render json: @post
tells Rails to render it immediately instead of looking for a file.
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.