Rails3有助于连接范围

时间:2011-03-27 18:00:21

标签: ruby-on-rails ruby-on-rails-3

拥有简单的订单 - 商品应用。没车。需要有关我的报告的联接范围的帮助。

项目是多态的(belongs_to :itemable, :polymorphic => true),包含产品,服务和政策。政策属于Vendor。

目标是列出供应商销售的数量,但仍然可以使用订单范围,如下所示。

我的订单模型中的范围

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 closed_date >= ? AND closed_date < ?", nil, Time.now.midnight.yesterday, Time.now.midnight)}
...

类似于 - 在订单模型中猜猜?

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

最终结果可以按供应商分组并获得销售金额。

<% 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) %>

价格是项目字段,用于保存该商品的销售量。

我知道你不能如上所示进行分组,因此任何关于如何做到这一点的指针都会很棒。我想避免将vendor_id添加到我的Items表中。


更新

这是我最终做的事情。 为项目添加了vendor_id。让我的生活更轻松。当然,这是一种更好的方法。

在我的项目模型中

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

在我看来(因为@ orders.closed_today实际上是从另一个视图传入的。)

<% 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>

1 个答案:

答案 0 :(得分:0)

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