我使用腳手架爲帖子創建了CRUD系統。在控制器中,我看到:瞭解Ruby/Rails中的塊
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
什麼是
respond_to
和它從何而來?由於它使用的是運算符do
,因此我假設它是某種可迭代列表。在該列表中的每個format
上,它將執行html
和json
方法。{ render json: @posts }
與json
方法有什麼關係?是否將render json: @posts
作爲該方法的參數傳遞?每個對象是render
和json
?我從來沒有見過在符號之外使用冒號符號。
謝謝,這非常有幫助。在Ruby語法中,似乎只有很多方法可以實現同樣的功能,而我不習慣每種方式來閱讀。 –