I used scaffolding to create a CRUD system for posts. In the controller, I see this:
class PostsController < ApplicationController
# GET /posts
# GET /posts.json
def index
@posts = Post.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @posts }
end
end
-
What is
respond_toand where does it come from? Since it is using thedooperator, it is some sort of iterable list, I’m assuming. On eachformatin that list, it will perform thehtmlandjsonmethods. -
How does
{ render json: @posts }work in relation to thejsonmethod? Isrender json: @postsbeing passed as an argument to the method? Isrenderandjsoneach an object? I’ve never seen the colon notation used outside of symbols.
responds_tocomes from. The subject there worth looking into is “method lookup”.do ... endis one way of writing a block.{ render json: @posts }is another way.json: "foo"is a more modern alternative to writing:json => "foo"formatis an arbitrary variable you’re cooking up to use inside the block.renderis a method and:jsonis a symbol.respond_towill respond to user requests that Rails format responses accordingly.http://apidock.com/rails/ActionController/MimeResponds/InstanceMethods/respond_to
And if you want to look at the source (it’s a little thick), for example at the
respond_withmethod that Paul mentioned, that’s in the Rails source here:rails/actionpack/lib/action_controller/metal/mime_responds.rb