2015-10-12 41 views
0

我正在嘗試搜索Order已完成的所有LineItems。Spree,Rails LineItems只能獲得屬於已完成訂單的訂單

# /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?

這種方式是也沒關係:product.orders.complete ...但不知道如何通過搜索LineItems它的variant_id。

我該如何解決?如何返回屬於已完成訂單的所有產品的LineItem?
非常感謝!

回答

0

啊。好的,想通了。

最後這個解決它,請注意我改表名從ordersspree_orders

product.line_items.joins(:order).where.not(spree_orders: { completed_at: nil }) 

而且,可以用.includes(:order)做,但它似乎更長時間的查詢,需要比.joins(:order)長一點點。

0

你可以做到這一點很容易這樣說:

# 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 

現在,你就可以打電話orders_completedproduct

product.orders_completed 

和,然後您可以鏈接任何地方與此:

product.orders_completed.where(...) 
+1

謝謝大家,稍後嘗試一下,可能會比我的解決方案更快。 – muzykabart