我已经尝试了一百万种方式,我无法弄明白,
如何从视图中访问以下方法的quantitymy和createddate(在模型中)?
def self.groupit
group("hour(created_at)").select("count(*) as quantitymy, hour(created_at) as createddate")
end
我确定我完全错了,小组的事情也不起作用, 有人可以帮忙吗? 谢谢:))
更新: 我有一个User模型,一个Group模型和一个Post模型。
用户属于一个群组,帖子属于用户。帖子仅通过用户属于群组。
我试图显示在群组中发布的所有帖子,按时间分组。 所以它应该是
Group 1: 1 post at 13:00, 5 posts at 14:00
Group 2: 17 posts at 12:00, 1 post at 13:00, 2 posts at 14:00
等
我通过控制器显示它:
@groups = Group.all
然后在视图中循环显示:
<% @groups.each do |g| %>
<% if g.posts.exists? %>
<tr>
<td><b><%= g.name %></b>;
<%= g.posts.count %> posts
<% g.posts.each do |post| %>
<%= post.created_at.strftime("%H") %>:00;
<% end %>
</td>
<% else %>
<% end %>
</tr>
<% end %>
更新2 /答案:
<% @groups.each do |g| %>
<% if g.posts.exists? %>
<tr>
<td><b><%= g.name %></b>;
<%= g.posts.count %> posts
<% g.posts.group("hour(posts.created_at)").count("hour(posts.created_at)").each do |created_at, quantitymy| %>
<%= created_at %>; <%= quantitymy %>
<% end %>
</td>
<% else %>
<% end %>
</tr>
<% end %>
答案 0 :(得分:0)
我想你想要这样的东西:
group("hour(created_at)").count("hour(created_at)")
这将为您提供一个有序哈希,其中键是小时(created_at)值,值是计数。
您可以这样显示:
Group.group("hour(created_at)").count("hour(created_at)").each do |created_at, quantitymy|
# ...
end