Jbuilder在控制器中的基本用法
Basic usage of Jbuilder in a controller
在 Rails (5.2) 应用程序中,我尝试使用 JBuilder 来 return 一些 JSON 作为响应。
我在 Gemfile
.
中添加了 JBuilder
# Gemfile
...
gem 'jbuilder', '~> 2.5'
...
# Gemfile.lock
...
jbuilder (2.8.0)
...
根据 JBuilder 文档:
You can also extract attributes from array directly.
@people = People.all
json.array! @people, :id, :name
=> [ { "id": 1, "name": "David" }, { "id": 2, "name": "Jamie" } ]
现在,在我的控制器中,我添加了以下内容:
def index
respond_to do |format|
format.json { render json.array! User.all, :email, :full_name }
end
end
但我明白了
NameError - undefined local variable or method `json' for
UsersController:0x00007fe2f966f150 16:55:40 rails.1
| => Did you mean? JSON:
我在这里遗漏了什么吗?
您通常在扩展名为 .json.jbuilder
的视图文件中使用 jbuilder
在你的控制器中:
def index
@users = User.all
respond_to do |format|
format.json
end
end
在你的app/views/users/index.json.jbuilder
json.array! @users, :email, :full_name
编辑:您也可以像这样从控制器中进行操作:
format.json { render json: Jbuilder.new { |json| json.array! User.all, :email, :full_name }.target! }
你可以这样做:
def index
Jbuilder.new do |json|
json.array! User.all, :email, :full_name
end.attributes!
end
(对我有用)
旁注
您可能会看到人们在做:
Jbuilder.encode do |json|
# ...
end
但是Jbuilder.encode
实际上returns一个字符串,在源代码this comment中指定
在 Rails (5.2) 应用程序中,我尝试使用 JBuilder 来 return 一些 JSON 作为响应。
我在 Gemfile
.
# Gemfile
...
gem 'jbuilder', '~> 2.5'
...
# Gemfile.lock
...
jbuilder (2.8.0)
...
根据 JBuilder 文档:
You can also extract attributes from array directly.
@people = People.all
json.array! @people, :id, :name
=> [ { "id": 1, "name": "David" }, { "id": 2, "name": "Jamie" } ]
现在,在我的控制器中,我添加了以下内容:
def index
respond_to do |format|
format.json { render json.array! User.all, :email, :full_name }
end
end
但我明白了
NameError - undefined local variable or method `json' for UsersController:0x00007fe2f966f150 16:55:40 rails.1
| => Did you mean? JSON:
我在这里遗漏了什么吗?
您通常在扩展名为 .json.jbuilder
在你的控制器中:
def index
@users = User.all
respond_to do |format|
format.json
end
end
在你的app/views/users/index.json.jbuilder
json.array! @users, :email, :full_name
编辑:您也可以像这样从控制器中进行操作:
format.json { render json: Jbuilder.new { |json| json.array! User.all, :email, :full_name }.target! }
你可以这样做:
def index
Jbuilder.new do |json|
json.array! User.all, :email, :full_name
end.attributes!
end
(对我有用)
旁注
您可能会看到人们在做:
Jbuilder.encode do |json| # ... end
但是Jbuilder.encode
实际上returns一个字符串,在源代码this comment中指定