【发布时间】:2018-01-29 21:18:46
【问题描述】:
我有一个名为 RequestForm 的模型,我想在我的示例 Web 界面中呈现种子数据。
这个模型的结构是这样的:
表:
create_table "request_forms", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.date "request_date"
t.string "submit_by"
t.string "submit_to"
t.string "requester_name"
end
种子数据:
RequestForm.delete_all
RequestForm.create! (
[
{
requester_name: "David",
request_date: Date.new(2017,1,2)
},
{
requester_name: "Mike",
request_date: Date.new(2018,1,3)
},
{
requester_name: "Jack",
request_date: Date.new(2018,1,3)
}
]
)
控制器如下所示:
class Api::RequestFormsController < ApplicationController
def show
@RequestForm = RequestForm.find(param[:id])
end
def index
@RequestForms = RequestForm.all
end
end
它也在 routes.rb 中提供资源
namespace :api, defaults: { format: :json } do
resources :request_forms, only: [ :index, :show ]
end
当我尝试用一行创建一个 jbuilder 文件时:
json.extract! @RequestForms, :requester_name, :request_date
这就是 500(内部服务器错误)发生的地方。我点击进入错误消息,它说:
undefined method `requester_name' for #<RequestForm::ActiveRecord_Relation:0x00007f2c0a879f28>
我不知道为什么它期待一个关系,因为从这里链接中的文档:http://www.rubydoc.info/github/rails/jbuilder/Jbuilder:extract!
Extracts the mentioned attributes or hash elements from the passed object and turns them into attributes of the JSON.
我只是按照它提供的示例进行操作。那么我在这里做错了什么?
【问题讨论】: