[英]Spree, Rails LineItems get only those that belongs_to completed Order
我正在嘗試搜索訂單已完成的所有LineItem。
# /spree/order.rb
def self.complete
where.not(completed_at: nil)
end
我試過了:
product.orders.complete.map { |o| o.line_items }.flatten
但它返回一個數組,我不能做.where(variant_id: ID)
。
要么:
product.orders.includes(:line_items).complete.where(line_items: { variant_id: 263})
但它說: PG::UndefinedTable: ERROR: missing FROM-clause entry for table "line_items"
然后我嘗試了:
product.line_items.includes(:order).where(variant_id: ID).where.not(order: { completed_at: nil })
它返回ActiveRecord::ConfigurationError: Association named 'orders' was not found on Spree::LineItem; perhaps you misspelled it?
ActiveRecord::ConfigurationError: Association named 'orders' was not found on Spree::LineItem; perhaps you misspelled it?
這樣也可以: product.orders.complete ...
但是不知道如何通過其variant_id搜索LineItems。
我該如何解決? 如何返回屬於已完成Order的所有Product的LineItem?
非常感謝!
啊 好,知道了
最后用這個解決了,注意我將表名從orders
更改為spree_orders
:
product.line_items.joins(:order).where.not(spree_orders: { completed_at: nil })
並且,可以使用.includes(:order)
來完成,但是它看起來要比.joins(:order)
更長的查詢時間,並且花費的時間更長。
您可以通過以下方式輕松完成此操作:
# in Order Model (order.rb)
scope :completed, -> { where.not(completed_at: nil) }
# in Product Model (product.rb)
has_many :orders
delegate :completed, to: :orders, prefix: true
現在,您將可以調用product
orders_completed
:
product.orders_completed
然后,您可以使用以下方法在任何位置進行鏈接:
product.orders_completed.where(...)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.