简体   繁体   English

HMT或HABTM用于订单和物品

[英]HMT or HABTM for Orders and Items

Fairly new to rails and trying to understand which relationships to use before going forward. 对Rails来说还很陌生,并且在继续之前尝试了解要使用的关系。

I have two models: orders and items . 我有两种模型: ordersitems This is a many to many relationship, but I'm unsure of which relationship to use. 这是一个多对多关系,但是我不确定要使用哪种关系。

Orders might have delivery time, quantity of items, etc. 订单可能有交货时间,物品数量等。

Lastly, what would you call the model joining orders and items if using HMT? 最后,如果使用HMT,您将如何称呼加入ordersitems的模型?

If you need to know anything else about the relationship of the item on a particular order, you need HMT. 如果您需要了解有关特定订单上物料关系的其他信息,则需要 HMT。

If your items change price in the future, do you want to know how much they were sold for on orders in the past? 如果您的商品将来会改变价格,您是否想知道它们过去在订单上的售价是多少?

In this type of requirement, I've always had many "LineItem" records for an order, and the line_item instances belong_to to the item and order, and record the pricing and/or quantity for that order. 在这种类型的需求中,我一直有很多“ LineItem”记录用于订单,并且line_item实例属于该物料和订单,并记录该订单的价格和/或数量。

HMT vs HABTM? HMT与HABTM? There are so few times that all you need is a many-to-many, that I'd almost always go with HMT for the extra ability to add more information to the association. 有那么几次, 所有你需要的是一个多到很多,我会几乎总是与HMT去到更多的信息添加到关联额外的能力。

This seems like a classic case of HABTM, and the example given in the Rails Guides is perfect. 这似乎是HABTM的经典案例, Rails指南中给出示例非常完美。 The choice comes down to whether you need any other data or logic on the join model itself. 选择取决于您是否需要联接模型本身上的任何其他数据或逻辑。 If so, then use the HMT, where you will create a third active_record model to serve as the join table. 如果是这样,则使用HMT,您将在其中创建第三个active_record模型作为联接表。 You can name that anything you want. 您可以随便命名。 But it seems like HABTM will work for you, and all you need to setup is the join table with the default name ( items_orders ) in your migration, and rails will take care of everything else for you. 但是似乎HABTM会为您工​​作,并且您需要设置的只是items_orders表,该表具有您迁移中的默认名称( items_orders ),而rails会为您完成所有其他工作。

class Order < ActiveRecord::Base
  has_and_belongs_to_many :items
end

class Item < ActiveRecord::Base
  has_and_belongs_to_many :orders
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM