尝试使用belongs_to assoc从不同的模型渲染params时的未定义方法

时间:2016-08-26 16:29:01

标签: ruby-on-rails

尝试在模型发票视图中呈现模型 Billingitem 的值 - 我正在使用Rails 4.1,因此我将它们作为强大的参数包含在Controller中:

class InvoicesController < ApplicationController

  private
    def invoice_params
      params.fetch(:invoice, {}).permit(:issue_time, :total, :vat_id, :amount,
          :item, :currency, :client_id, :invoice, :quarter, :pdf, 
          :recurringmonthly, :recurringbiweekly, :expense,
          billingitems_attributes: [ :id, :name, :quantity, :price ])
    end

end

协会也在模型中:

class Invoice < ActiveRecord::Base

  has_many :billingitems
  accepts_nested_attributes_for :billingitems

end

class Billingitem < ActiveRecord::Base
  belongs_to :invoice
end

在控制台中,我可以正确地看到值(例如&gt; Invoice.find(76).billingitems.name并返回一个值)如果我尝试对Invoice.find等任何其他参数执行相同操作(76 ).billingitems.quantity或Invoice.find(76).billingitems.price我总是在控制台和视图中得到undefined method priceundefined method quantity。为什么呢?

1 个答案:

答案 0 :(得分:0)

正如@fanta所说,billingitems是一个集合。所以你应该做这样的事情

Invoice.find(76).billingitems.each do |billingitem|
  billingitem.name
  billingitem.quantity
  billingitem.price
end