This is the default Rails code generated. I understand what the code does (from the explanation in the documentation) but not how it does.
1 class PostsController < ApplicationController
2 # GET /posts
3 # GET /posts.json
4 def index
5 @posts = Post.all
6
7 respond_to do |format|
8 format.html # index.html.erb
9 format.json { render json: @posts }
10 end
11 end
What I understand:
Post.all
returns an array of all the posts which is saved in the instance variable @postsrespond_to
function takes the default 'block' (an anonymous function block which takes one parameter 'format'- Depending on the requested format, corresponding output is returned
What I don't understand:
- How does that actually work? Line# 8 calls a function
html
method offormat
object, no matter whatever format is passed. What does thehtml
method do? Why both methods are called every time? Are they? - Why does
json
method require an argument (block that calls render) buthtml
method does not need any argument - Does this function return anything? It looks like it returns the return value of
json
method.
I am new to ruby and rails and I am getting started with example and would like to know in detail what each line does.