【问题标题】:How to make this active record associations如何使这个活动记录关联
【发布时间】:2011-11-30 06:33:25
【问题描述】:

我有一个

物品模型

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 的方法是什么?

【问题讨论】:

    标签: ruby-on-rails ruby database-design activerecord


    【解决方案1】:

    一种方法是使用 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。

    您可以在A Guide to Active Record AssociationsThe has_many :through Association 部分阅读有关这些关系的更多信息。

    【讨论】:

      猜你喜欢
      • 2016-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多