2011-03-27 47 views
2

@orders.closed_today是今天關閉的所有訂單的數組。Rails從所有訂單中獲取所有項目

我該如何列出所有這些項目?

@items = @orders.closed_today.items


更新 報告HTML

<% @items = Item.in_orders(@orders.closed_today) %> 

項目模型

scope :in_orders, lambda { |orders| where('order_id is in (?)', orders.map(&:id).join(',')) } 

回答

1

簡單:映射的項目。

@items = @orders.closed_today.all(:include => :items).map(&:items) 

這會給你:

=> [[item1,item2],[item2,item3]] 

爲了得到獨一無二的項目:

@orders.closed_today.all(:include => :items).map(&:items).flatten.uniq 

這不是獲取相關對象的一種可持續的方式;注意N + 1性能問題。

更一般地,你應該做這樣的事情:

class Item 
    scope :closed_today, joins(:orders) & Order.closed_today 
end 

,只是稱:

Item.closed_today 
+0

這種類型的工作。需要將結果展平爲單個[]。在http://stackoverflow.com/questions/4307411/not-in-rails中的某處,我可以搜索Item.order_id是否在@ orders.closed_today中。當試圖在鏈接答案得到了一個SQLite3 :: SQLException:近「in」:語法錯誤:更新的問題,以顯示我試過。 – pcasa 2011-03-27 20:27:16

+0

使用訂單上的範圍添加項目的範圍;這更多的是你要找的,對嗎? – 20man 2011-03-27 22:58:51

+0

將範圍轉爲lambda以靈活使用範圍日期範圍。謝謝! – pcasa 2011-03-28 00:01:43

相關問題