Rails get all items from all orders
@orders.closed_today
is an array of all orders closed for today.
How can I list get all the items for this?
i.e. @items = @orders.closed_today.items
Update Reports html
<% @items = Item.in_orders(@orders.closed_today) %>
Items model
scope :in_orders, lambda { |orders| where('or开发者_如何学编程der_id is in (?)', orders.map(&:id).join(',') ) }
Simple: map the items.
@items = @orders.closed_today.all(:include => :items).map(&:items)
That will give you:
=> [[item1,item2],[item2,item3]]
To get unique items:
@orders.closed_today.all(:include => :items).map(&:items).flatten.uniq
This is not a sustainable way of fetching related objects; beware N+1 performance problems.
More generally, you should probably do something like this:
class Item
scope :closed_today, joins(:orders) & Order.closed_today
end
and just call:
Item.closed_today
精彩评论