【问题标题】:Products, Orders, and Customers Rails Associations产品、订单和客户 Rails Associations
【发布时间】:2013-02-10 23:50:07
【问题描述】:

我正在尝试找出适合我的模型的 ActiveRecord 关联。我想创建一个非常准系统的电子商务网站。我想拥有一个升级和维修产品的系统,因此访问用户的订单历史记录很重要。

我目前的设置如下:

用户

has_many :products, :through => :orders

has_many :orders, :dependent => :destroy

订单

belongs_to :user

has_many :products

产品

belongs_to :orders

我的第一个问题是这有意义吗?我关心 Products 的 belongs_to :orders 部分,因为我想确保一个产品可以成为许多不同订单的一部分(出于显而易见的原因)。如果这是错误/正确的,正确的关系需要哪些必要的迁移?

提前致谢。

【问题讨论】:

  • 您需要在 Product 和 Order 模型之间建立多对多的关系。不想使用连接表可以使用has_and_belongs_to_many关联,否则只有一个选项has_many :through
  • 如果我使用 HABTM,那么语义听起来不正确,但我明白你的意思。看起来我想要我认为不存在的“belongs_to_many”。谢谢你们的帮助。
  • 没有。不需要belongs_to_many,因为它类似于现有的has_many :throughHABTMbelongs_to 用于我们保留foreign key 的关联一侧。那么,您如何处理belongs_to_many?必须有另一个连接表来处理这个问题,如果是这种情况,那么可以通过现有的 many to many 关联来完成。

标签: ruby-on-rails activerecord associations


【解决方案1】:

我意识到这篇文章已经很老了,但由于我遇到了同样的问题,所以为关注者增加一些清晰度可能会很有趣。正如@ManojMonga 在 cmets 中所说,在这里您需要使用 has_and_belongs_to_many 关联。所以模型看起来像:
用户

has_many :orders, :dependent => :destroy
has_many :products, through: :orders

订购

belongs_to :user
has_and_belongs_to_many :products

产品

has_and_belongs_to_many :orders

然后,如Active Record Association Rails Guide 中所述,您将需要创建一个连接表来保存订单和产品外键。迁移看起来像这样:

class OrdersProducts < ActiveRecord::Migration
  def change
    create_table :orders_products, id: false do |t|
      t.belongs_to  :order, index: true
      t.belongs_to  :product, index: true
      t.timestamps
    end
  end
end

然后,在您运行迁移之后,您将能够使用has_and_belongs_to_many methods。 请记住,当您创建连接表时,在 has_an_belongs_to_many 关联中,Active Record 将查找以字母顺序连接的 2 个表名命名的表。如果您想以其他方式命名它,则必须在模型中指定它,如下所示:
订购

has_and_belongs_to_many :products, :join_table => "new_tables_name"

产品

has_and_belongs_to_many :orders, :join_table => "new_tables_name"

最后,用户模型中的the has_many :products, through: :orders 不是强制性的。它只允许通过用户访问产品。 就是这样,如果能帮上忙,我会很高兴的。顺便说一句,我使用的是 Rails 4.1。

【讨论】:

    【解决方案2】:

    产品has_one :order。这将允许您使用 @product.order 之类的东西,但它实际上不会为产品数据库表中的订单创建外键。

    【讨论】:

    • 但该措辞暗示对于每个产品,都有一个订单。我想确保一个产品可以成为来自不同用户的许多不同订单的一部分。我希望能够使用 user.products 和 order.products 之类的东西,但要确保产品不只与一个订单或用户相关联。即用户 A 和用户 B 在不同日期以不同的订单订购了产品 A。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-26
    • 1970-01-01
    • 2018-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-22
    相关资源
    最近更新 更多