【问题标题】:Order, Product and OrdersProduct models associationsOrder、Product 和 OrdersProduct 模型关联
【发布时间】:2016-04-05 12:34:55
【问题描述】:

我正在构建一个 Rails 应用程序,其中我需要有 Product 和 Order 模型。

我认为逻辑路径是有另一个模型,称为 OrdersProduct,因为一个订单可以有许多要订购的产品,我在其中放置了一个 product_idorder_id(匹配其他两个模型)和一个 @ 987654323@字段。

好吧,我的问题是如何从我的 OrdersProduct 记录中访问每个产品信息?

重点是我可以将belongs_to :product 关联到我的OrdersProduct 模型中,但是将has_many :orders_products 放在我的Product 模型中没有任何意义。

模型看起来像这样:

class Customer < ActiveRecord::Base
  # id
  # name
  # etc…
end

class Product < ActiveRecord::Base
  # id
  # name
  # etc…
end

class Order < ActiveRecord::Base
  # id
  # customer_id
  # etc…
end

class OrdersProduct < ActiveRecord::Base
  # order_id
  # product_id
  # amount
end

访问Order.products 并获取与 OrdersProduct 模型相关的产品集合的最佳方式是什么?

【问题讨论】:

    标签: ruby-on-rails activerecord associations


    【解决方案1】:

    你想要的是使用Has and belongs to many through关联。

    class Order < ActiveRecord::Base
      has_many :orders_products
      has_many :products, through: :orders_products
    end
    
    class Product < ActiveRecord::Base
      has_many :orders_products
      has_many :orders, through: :orders_products
    end
    
    class OrdersProduct < ActiveRecord::Base
      belongs_to :order
      belongs_to :product
    end
    

    现在在商业术语中,订购的产品通常称为LineItem,因此您可以指定line_items 表,而不是使用orders_products 表。

    class Order < ActiveRecord::Base
      has_many :line_items
      has_many :products, through: :line_items
    end
    
    class Product < ActiveRecord::Base
      has_many :line_items
      has_many :orders, through: :line_items
    end
    
    class LineItem < ActiveRecord::Base
      belongs_to :order
      belongs_to :product
    end
    

    【讨论】:

    • 谢谢,非常准确。我一会儿试试看!
    • 什么是def Order &lt; ActiveRecord::Base
    • 感谢您发现错误。我在输入答案时很着急。
    • 这工作非常顺利。谢谢约瑟夫。也适用于 LineItem 提示。我不是英语,但我更喜欢用英语编写我的代码,以前不知道这一点。
    【解决方案2】:

    您可以摆脱OrdersProduct 模型。

    只需要以下型号:

    class Customer < ActiveRecord::Base
      has_many :orders
      # id
      # name
      # etc…
    end
    
    class Order < ActiveRecord::Base
      belongs_to :customer
      has_many :products
    
      # id
      # customer_id
      # etc…
    end
    
    class Product < ActiveRecord::Base
      belongs_to :order
    
      # id
      # name
      # order_id
      # etc…
    end
    

    所以现在您可以调用customer.orders.first.productsorder.products,因为customerorder 是实例。

    【讨论】:

    • 不要认为这有帮助。您需要加入模型来处理多对多关系并跟踪有关连接的其他信息(金额、折扣等)。
    • 无处可去,这就是为什么我认为它没有帮助。
    • 我认为这是多对多关系的典型用例。每次用户将产品添加到订单时,您想为产品创建新记录吗?那么您将在哪里获得产品详细信息/信息?如果您不信任我,请查看 github.com/spree/spree 他们如何处理在线商店。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-23
    • 1970-01-01
    • 1970-01-01
    • 2011-12-24
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多