在多个关联中查找记录

时间:2019-06-28 03:07:00

标签: ruby-on-rails ruby

我想通过多个关联级别查找多个记录。

我需要使用以下命令遍历Orders模型:

命令Order.cart.line_items(通过line_items迭代)

line_item.shop_product.product == vendor_products

我目前正在这样做:

vendor_products = VendorProduct.where(vendor_id: current_user.id)
vendor_shop_products = ShopProduct.where(product: vendor_products.map { |vp| vp.product_id})
vendor_line_items = LineItem.where(shop_product: vendor_shop_products)
vendor_carts = Cart.where(line_items: vendor_line_items)
vendor_orders = Order.where(cart: vendor_carts)

我想知道并且还假设有很多更好的方法可以做到这一点。我该如何缩短?

型号:

class LineItem < ApplicationRecord
  belongs_to :shop_product, optional: true
  belongs_to :product, optional: true
  belongs_to :cart

class Order < ApplicationRecord
  belongs_to :cart, optional: true

class Product < ApplicationRecord
  has_one :shop_product
  has_one :vendor_product

class ShopProduct < ApplicationRecord
  belongs_to :product, optional: true
  has_one :order

class VendorProduct < ApplicationRecord
  belongs_to :product
  belongs_to :vendor, :class_name => "User"

class Cart < ApplicationRecord
  has_many :line_items, dependent: :destroy
  has_one :order

1 个答案:

答案 0 :(得分:1)

我将从以下内容开始:

Order.joins(cart: { line_items: { product: { vendor_product: :vendor } } })
     .where(vendor: { id: current_user.id })

Rails指南中的有用读物: