Ruby on rails 如何使用:through获取多个额外数据?
我有一个典型的模型设置:Ruby on rails 如何使用:through获取多个额外数据?,ruby-on-rails,ruby-on-rails-3,ruby-on-rails-3.1,Ruby On Rails,Ruby On Rails 3,Ruby On Rails 3.1,我有一个典型的模型设置: Store has_many Items Orders has_many Items :through OrderItems OrderItems 但是,在OrderItems上,我有一个名为“quantity”的字段来告诉我每个项目在订单上的数量。我不知道如何正确地检索这些信息 ex. Order.find(1).order_items # has the list of items, but no "quantity" field 有什么想法吗?我也有同样的情况
Store has_many Items
Orders has_many Items :through OrderItems
OrderItems
但是,在OrderItems上,我有一个名为“quantity”的字段来告诉我每个项目在订单上的数量。我不知道如何正确地检索这些信息
ex. Order.find(1).order_items # has the list of items, but no "quantity" field
有什么想法吗?我也有同样的情况。我用了另一种联想。比如
Store has_many Items
Orders has_many Items :through OrderItems
Orders has_many OrderItems
它将使用相同的order_id进行映射,然后
Order.find(1).order_items # has the list of order_items, with "quantity" field in there
我有一个类似的问题: 您遇到的问题是,您试图在订单散列中获取属性order\u项。即使您告诉rails只查找(1),它仍然会抓取一个散列,因为它不知道在查找(1)时只会抓取一个项目。我相信如果您执行
Order.find(1).first.Order\u items.quantity
(不是100%确定这会起作用),那么应该会起作用,因为您告诉rails只会检索到一件东西。此外,您还可以通过执行以下操作循环检索到的订单:
@orders = Order.find(1)
@orders.each do |order|
order.order_items.quantity
end
但是,如果您试图获取订单项的“计数”,则需要使用.count而不是.quantity。您的问题有点让人困惑。您是否能够“连接”项目和订单@item,以便@item上的“数量”属性?您可以在项目模型中执行相同的操作,就像项目有许多订单项目一样。然后item.find(1)。订单项目将为您提供数量列表。我不知道,这是您的问题吗?或者请澄清你的问题。我意识到你是对的。我可以订购商品,商品信息就在那里。谢谢