【发布时间】:2011-03-27 18:00:20
【问题描述】:
有简单的订单 - 项目应用程序。没有购物车。在我的报告的连接范围方面需要帮助。
项目是具有产品、服务和策略的多态 (belongs_to :itemable, :polymorphic => true)。政策属于供应商。
目标是列出供应商销售了多少,但仍然能够使用订单范围,如下所示。
我的订单模型中的范围
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) %>
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>
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3