【发布时间】:2016-01-17 09:31:52
【问题描述】:
这是默认生成的 Rails 代码。我了解代码的作用(来自文档中的解释),但不了解它的作用。
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
我的理解:
-
Post.all返回保存在 实例变量@posts -
respond_to函数采用默认值 'block'(一个匿名功能块,它接受一个参数 '格式' - 根据请求的格式,返回相应的输出
我不明白的:
- 这实际上是如何工作的?第 8 行调用
format对象的函数html方法,无论传递何种格式。html方法有什么作用?为什么每次都调用这两种方法?是吗? - 为什么
json方法需要参数(调用渲染的块)而html方法不需要任何参数 - 此函数是否返回任何内容?看起来它返回了
json方法的返回值。
我是 ruby 和 rails 的新手,我开始使用示例,想详细了解每行的作用。
【问题讨论】:
标签: ruby-on-rails ruby model-view-controller respond-to