以下是我想要排序的模型。
我有一个User
,可以拥有多个Post
,而且每个Statistic
都有class User < ActiveRecord::Base
has_many :posts
has_many :statistics
end
class Post < ActiveRecord::Base
belongs_to :user
has_many :statistics
end
class Statistic < ActiveRecord::Base
belongs_to :post
belongs_to :user
end
。
总结这就是我所拥有的:
# Group by day all statistics from one user
stats_by_date = current_user.statistics.group_by { |s| s.created_at.to_date }
# Transform the hash into an Array (one cell = one day)
@overall_statistics = stats_by_date.values
最后我想要的是两张桌子(一个牢房=一天):
对于第一个,我已经使用:
完成了# Group statistics by posts
stats_by_post = current_user.statistics.group_by { |s| [s.created_at.to_date, s.post_id] }
对于第二个,我成功地将我的结果分组为Post ID和days但我不知道如何将其转换为可利用的数组,这意味着每个Post ID和每个表中有一个表细胞一天:
{
#[Thu, 07 May 2015, 2]=>[#<Statistic id: 68>, #<Statistic id: 69>, #<Statistic id: 74>],
#[Thu, 08 May 2015, 1]=>[#<Statistic id: 70>, #<Statistic id: 71>, #<Statistic id: 72>, #<Statistic id: 73>, #<Statistic id: 80>],
#[Thu, 08 May 2015, 2]=>[#<Statistic id: 70>, #<Statistic id: 71>, #<Statistic id: 72>, #<Statistic id: 73>, #<Statistic id: 80>],
# ...
}
以下是我得到的哈希:
#--Table for : Post ID 2
#----First Cell (Thu, 07 May 2015)
#------[#<Statistic id: 68>, #<Statistic id: 69>, #<Statistic id: 74>]
#----Second cell (Thu, 08 May 2015)
#------[#<Statistic id: 70>, #<Statistic id: 71>, #<Statistic id: 72>, #<Statistic id: 73>, #<Statistic id: 80>]
#--Table for : Post ID 1
#----First Cell (Thu, 07 May 2015)
#------[#<Statistic id: 70>, #<Statistic id: 71>, #<Statistic id: 72>, #<Statistic id: 73>, #<Statistic id: 80>]
如何为每个帖子创建一个表?
我想要的是:
holder.imagen.setImageDrawable(trofeos.getDrawable(position-1));
holder.puntos.setText(getItem(position-1).toString().substring(0,
getItem(position-1).toString().length() - 19));
holder.fecha.setText(getItem(position-1).toString().substring(
getItem(position-1).toString().length() - 19,
getItem(position-1).toString().length()));
答案 0 :(得分:5)
我可以看到两种构建嵌套哈希的方法:
group_by
:statistics_by_post = current_user.statistics.group_by(&:post_id)
@statistics_by_day_by_post = statistics_by_post.map do |p_id, stats|
[p_id, stats.group_by{ |s| s.created_at.to_date }]
end.to_h
@statistics_by_day_by_post = {}
current_user.statistics.each do |s|
post_id, day = s.post_id, s.created_at.to_date
@statistics_by_day_by_post[post_id] ||= {}
@statistics_by_day_by_post[post_id][day] ||= []
@statistics_by_day_by_post[post_id][day] << s
end
HTH!