开发者

Rails3 help with joins scope

Have simple Order - Item app. No cart. Need help with joined scopes for my reports.

Item is polymorphic (belongs_to :itemable, :polymorphic => true) with Products, Services and Policies. Policies belongs to Vendor.

Goal is list out how much was sold by Vendor but still be able to use the scopes for Orders as seen below.

Scopes in my Orders model

scope :closed_today, lambda { where("closed_date IS NOT ? AND closed_date >= ? AND closed_date < ?", nil, Time.now.midnight, Time.now.midnight.tomorrow)}
scope :closed_yesterday, lambda { where("closed_date IS NOT ? AND clo开发者_开发技巧sed_date >= ? AND closed_date < ?", nil, Time.now.midnight.yesterday, Time.now.midnight)}
...

Something like - Guess in Orders Model?

scope :with_policies, joins(:items).where(:itemable_type => "Policy")

And Final Result being able to group by vendor and get amounts sold.

<% for v in @orders.closed_today.with_policies.group("itemable.vendor_id") %>
  <%= v.somehow_get_to.vendor.name %> Sold: <%= v.somehow_get_to.collect.sum(&:price) %>

Price is the item field that holds how much that item sold for.

I know you can't group as shown above, so any pointers on how to do that would be great. Would like to avoid adding vendor_id to my Items table.


UPDATE

Here is what I ended up doing. Added vendor_id to items. Made my life easier. Sure this is a better way of doing this.

In my Items model

scope :in_orders_with, lambda { |orders, type| where('itemable_type IS ?', type).joins(:order) & orders }

In my view (since @orders.closed_today is actually passed in from another view.)

<% orders = @orders.closed_today %>
<p>
<% @items = Item.in_orders_with(orders, "Policy") %>
<% if !@items.blank? %>
  <% @items.group_by{ |o| o.vendor }.each do |vendor, items| %>
   <%= vendor.name %> <br />Qty Sold:<%= items.count %> Dollars Sold:<%= items.collect.sum(&:price) %><br /><br />
  <% end %>
<% else %>
  Nothing to report from Policies<br />
<% end %>
</p>


<% @orders.closed_today.with_policies.group_by{|o| o.itemable.vendor}.each do |vendor, orders| %>
  <%= vendor.name %> SOLD: <%= orders.sum(&:price) %>
<% end %>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜