【问题标题】:rails: undefined method for ActiveRecord_Relation with Jbuilderrails:使用 Jbuilder 的 ActiveRecord_Relation 的未定义方法
【发布时间】: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.

我只是按照它提供的示例进行操作。那么我在这里做错了什么?

【问题讨论】:

    标签: ruby-on-rails jbuilder


    【解决方案1】:

    由于您在 jbuilder 模板中使用@RequestForms,我假设您正在尝试呈现索引操作。

    json.extract! @RequestForms, :requester_name, :request_date
    

    在这种情况下,@RequestFormsRequestForm::ActiveRecord_Relation,而不是 RequestForm 对象。我认为您正在寻找的是 json.array! 来帮助您渲染您拥有的对象集合。

    例如,您可以这样做:

    json.array! @RequestForms do |request_form|
      json.requester_name request_form.requester_name
      json.request_date request_form.request_date
    end
    

    虽然,您拥有的代码非常接近工作。您可以简单地使用json.array! 直接从数组中提取属性,而不是json.extract!

    json.array! @RequestForms, :requester_name, :request_date
    

    official jbuilder documentation 显示这种技术如下:

    # @people = People.all
    
    json.array! @people, :id, :name
    
    # => [ { "id": 1, "name": "David" }, { "id": 2, "name": "Jamie" } ]
    

    【讨论】:

    • 所以json.array! @RequestForms, :requester_name, :request_datejson.extract! requestform, :requester_name, :request_date 都有效?
    • 是的。两者都应该工作。重要的一点是json.array! 对数组进行操作,json.extract! 对对象进行操作。
    • 我明白了,让我失望的是命名约定。使用json.extract! 时,对象名称应为 request_forms 而不是 requestform。多元化和蛇案例惯例改变了一切。现在它起作用了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-11
    • 1970-01-01
    • 2013-01-20
    相关资源
    最近更新 更多