【问题标题】:Rails3 help with joins scopeRails3 帮助连接范围
【发布时间】: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


    【解决方案1】:
    <% @orders.closed_today.with_policies.group_by{|o| o.itemable.vendor}.each do |vendor, orders| %>
      <%= vendor.name %> SOLD: <%= orders.sum(&:price) %>
    <% end %>
    

    【讨论】:

    • 关闭。 o.itemable.vendor 不起作用,不得不像这样强制它 o.items.last.itemable.vendor。
    • 展示你的模型以了解关系结构
    • 目前,通过策略。 Vendor_id 在策略表中,这就是为什么我只拉出出售的物品和 itemable_type == 策略的物品。
    • 那么订单呢?只需显示具有关联的模型
    • 分解并在 items 表中添加了 vendor_id。所以现在应该有所帮助。将更新问题以显示数据库和关系。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-22
    相关资源
    最近更新 更多