我有一个书籍模型,为了这个问题,它有 5 个字段(id、title、issue、release_date、print_run)。我正在尝试填充按标题分组的销售表,所以这是我 Controller 中的内容:
@books = Book.all.where("release_date > ?", "2012-05-01").where("print_run > ?", "1").group(:title)
在我看来,这是表格的一部分:
<% @books.each do |title| %>
<tr>
<td><%= title.title %></td>
<td class="text-center">
<% if title.print_run > 1 && title.release_date.between?((Date.today - 12.month).beginning_of_month, (Date.today - 12.month).end_of_month) %>
<%= title.print_run %>
<% else %>
0
<% end %>
</td>
</tr>
<% end %>
每本书每月发行一期,因此我设置了一个包含 14 列(标题、每月一列和总数)的表格。我想按月显示每个 TITLE 的 print_run,但是当我在 Controller 中使用 group(:title)
时,它只显示上个月的打印运行(但其余为 0) .如果我从 Controller 中删除 group(:title)
,它会在正确的月份显示所有打印运行,但每个问题都有自己的运行。
这里有几张图片可以说明这个问题。提前致谢!
最佳答案
仅供引用,我重新设计了所有东西......在我现在的 Controller 中:
@book = Book.where(:rdate => (Date.today - 12.month)..(Date.today - 1.month)).where("printrun > ?", "1").select("DISTINCT(title)").group("title").order("title")
...然后在我看来:
<%= Book.where(:title => title.title, :rdate => (Date.today - 1.month).beginning_of_month..(Date.today - 1.month).end_of_month).sum(:printrun) %>
现在 View 部分可能并不理想,我会在某个时候将其移至 Controller 中,但问题已解决。请注意,我必须在 Controller 中添加 select("DISTINCT(title)").group("title") 。第一部分解决了我的独特问题,但导致 PGError,因为 PostgreSQL 默认按 ID 明显分组。通过指定组(“标题”)我解决了这个问题(即使这看起来显然是多余的)。
希望这对遇到类似问题的下一个人有所帮助。
关于ruby-on-rails - 分组时不显示 Rails 记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30535092/