ruby-on-rails - 如何使这个事件记录关联

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

我有一个

元素模型

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/

相关文章:

ruby-on-rails - 如何根据 rails 中的语言环境动态设置字体?

mysql - Rails 4 .joins() 问题——不工作

ruby-on-rails - 从 Rails 中删除 Bootstrap

ruby-on-rails - Bluecloth v2.0.10 与 Windows 7 不工作

database-design - 如何在 DynamoDB 中将排序键设置为全局二级索引(另一个分区键)?

database - 当多个表共享一个公共(public)数据模型时,最好的数据库设计是什么?

MySQL多态连接条件与OR不使用索引

ruby-on-rails - 运行一个简单的 rails-api 项目返回 ActiveRecord::ConnectionNotEstablished 错误

ruby - Github 服务/Ruby Gem "eventmachine"Mac 安装问题

数据库设计 : accounting transaction table