Rails 3 - 从具有不同Where子句的相同子表中获取多个计数

时间:2015-02-04 06:13:40

标签: ruby-on-rails

我和Job Shifts之间存在关系,他们已经表明他们是否想申请这些工作(是,否或可能)。

我想列出工作班次以及表示是,否或可能的人数。

我当前的查询不起作用,我不知道为什么,我是Rails的新手,所以我也想知道是否有更多的Railish方式来做这件事。

enter image description here

def report_shift_detail
    @headers = ["id", "staffroom_id", "title", "Yes", "No", "Maybe"]
    @fields = [:id, :staffroom_id, :title, :count_yes, :count_no, :count_maybe]

    @sql = Shift.scoped
      .select("shifts.id, shifts.staffroom_id, shifts.title, count(application_yes.id) as count_yes, count(application_no.id) as count_no, count(application_maybe.id) as count_maybe")
      .joins("INNER JOIN shift_applications as application_yes ON application_yes.shift_id = shifts.id")
      .where("application_yes.sort = 'yes'")
      .joins("INNER JOIN shift_applications as application_no ON application_no.shift_id = shifts.id")
      .where("application_no.sort = 'no'")
      .joins("INNER JOIN shift_applications as application_maybe ON application_maybe.shift_id = shifts.id")
      .where("application_maybe.sort = 'maybe'")
      .group("shifts.id")
end

2 个答案:

答案 0 :(得分:1)

我发布部分答案,因为它可能有用。我没有一个很好的RUBY答案,因为我不够精通将其构造为RUBY,但我通过重构select语句使查询正常工作,我从一开始就写错了。

这是工作SQL

SELECT shifts.id, shifts.staffroom_id, shifts.title, 
    (select count(*) from shift_applications where shift_applications.shift_id = shifts.id AND (shift_applications.sort = 'yes')) as count_yes,
    (select count(*) from shift_applications where shift_applications.shift_id = shifts.id AND (shift_applications.sort = 'no')) as count_no,
    (select count(*) from shift_applications where shift_applications.shift_id = shifts.id AND (shift_applications.sort = 'maybe')) as count_maybe
FROM "shifts" 
WHERE "shifts"."deleted" = 'f' 
GROUP BY shifts.id

以下是我在Ruby中实现它的方法

count_yes = "(select count(*) from shift_applications where shift_applications.shift_id = shifts.id AND (shift_applications.sort = 'yes')) as count_yes"
count_no = "(select count(*) from shift_applications where shift_applications.shift_id = shifts.id AND (shift_applications.sort = 'no')) as count_no"
count_maybe = "(select count(*) from shift_applications where shift_applications.shift_id = shifts.id AND (shift_applications.sort = 'maybe')) as count_maybe"

@sql = Shift.scoped
  .select("shifts.id, shifts.staffroom_id, shifts.title, #{count_yes}, #{count_no}, #{count_maybe}")
  .group("shifts.id")

希望有人能看到更清洁的方法来做到这一点

答案 1 :(得分:0)

我会在这里猜测,请发布更多信息,如表格列和名称。我假设您有两个名为ShiftShiftApplication的模型,我可能会这样做:

在您的控制器中:

def report_shift_detail
  @shifts = Shift.all
end

在你的report_shift_detail.html.erb中,我会有类似的内容

<% @shifts.each do |shift| %>
<tr>
  <td> <%= shift.shift_applications.where(sort: 'yes').count %></td>
  <td> <%= shift.shift_applications.where(sort: 'no').count %></td>
  <td> <%= shift.shift_applications.where(sort: 'maybe').count %></td>
</tr>
<% end %>

当然,如果它在我的位置,我将在我的模型中定义范围,而不是在视图中执行where。这是我根据你的例子唯一可以管理的事情。