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_tomethod 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.jsonmethod 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:If you don’t provide a block to the
format.jsonmethod, Rails automagically will try and look insideviews/posts/for ashow.json.erbfile, and render that. In the method you provided,render json: @posttells Rails to render it immediately instead of looking for a file.