我有一个
元素模型
class Item < ActiveRecord:Base
has_and_belongs_to_many :orders
end
还有一个订单模型
class Order < ActiveRecord:Base
has_and_belongs_to_many : items
end
一个订单可以有很多项目,HABTM 会处理这些项目。但是我在哪里/如何存储所订购商品的数量?
例如: 假设 Order1 中有 Item1 和 Item2。现在我想存储与商品相关的数量,例如 Order1 有两个 Item1 和五个 Item2。
rails 的方法是什么?
最佳答案
一种方法是使用 has_many :through 关联。这会为订单和商品之间的连接表创建一个独立的实体。在你的情况下:
class Order < ActiveRecord::Base
has_many :invoices
has_many :items, :through => :invoices
end
class Invoice < ActiveRecord::Base
belongs_to :order
belongs_to :items
#Put in the migration for this table a column for quantity
end
class Item < ActiveRecord::Base
has_many :invoices
has_many :orders, :through => :invoices
end
我相信这会解决您的问题。这样,与 Item1 关联的 Order1 在 Invoice 表中的数量为 2,而 Item2 在 Invoice 表中的数量为 5。
您可以在 The has_many :through Association 中阅读有关这些关系的更多信息A Guide to Active Record Associations 中的部分.
关于ruby-on-rails - 如何使这个事件记录关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8322005/