Reputation: 10550
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_to
and where does it come from? Since it is using the do
operator, it is some sort of iterable list, I'm assuming. On each format
in that list, it will perform the html
and json
methods.
How does { render json: @posts }
work in relation to the json
method? Is render json: @posts
being passed as an argument to the method? Is render
and json
each an object? I've never seen the colon notation used outside of symbols.
Upvotes: 3
Views: 108
Reputation: 1834
responds_to
comes from. The subject there worth looking into is "method lookup".do ... end
is one way of writing a block.
{ render json: @posts }
is another way.json: "foo"
is a more modern alternative to writing :json => "foo"
format
is an arbitrary variable you're cooking up to use inside the block. render
is a method and :json
is a symbol. respond_to
will 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_with
method that Paul mentioned, that's in the Rails source here:
rails/actionpack/lib/action_controller/metal/mime_responds.rb
Upvotes: 3
Reputation: 5941
First of all, respond_to
isn't modern stuff in Rails. But I will provide reference to explanation anyway.
More modern helper is respond_with.
Probably, this screencast will be useful for you.
Upvotes: 1