未定义的方法`id&#39;对于#<activerecord :: associations :: collectionproxy [] =“”>

时间:2016-04-12 23:58:20

标签: ruby-on-rails-4 activerecord rails-activerecord

可能会出现一个重复的问题,但似乎找不到解决这个问题的方法。

我试图让Payments的所有Orders属于Customer

我有这个

# customer.rb
has_many :orders, dependent: :restrict_with_exception, class_name: "Shoppe::Order"

# order.rb
belongs_to :customer, class_name: 'Shoppe::Customer'

# payment.rb
belongs_to :order, class_name: 'Shoppe::Order'

# payment_controller.rb
def index
@payments ||= []
@customer_orders  = @customer.orders.ordered.load
  @customer_orders.each do |d|
  @payments << d.payments
  end
end

在视图中......

for payment in @payments
      tr
        td
          =  payment.id

我收到错误 -

undefined method `id' for #<ActiveRecord::Associations::CollectionProxy   []>

非常感谢您解决此问题的任何帮助

1 个答案:

答案 0 :(得分:0)

您的问题是,您正在将ActiveRecord::Associations::CollectionProxy个对象(collectionPayment个实例)插入到数组中。

含义:现在您的数组是multi-dimentional数组。所以,现在当你循环时,迭代器会让你collection而不是单个payment个对象。

解决方案: 您需要flatten集合

# payment_controller.rb
def index
@payments ||= []
@customer_orders  = @customer.orders.ordered.load
  @customer_orders.each do |d|
  @payments << d.payments
  end
end

@payments = @payments.flatten

现在每个项目都应该响应id方法

了解有关ActiveRecord::Associations::CollectionProxy的更多信息,请参阅 http://api.rubyonrails.org/classes/ActiveRecord/Associations/CollectionProxy.html

让我知道这是否有效