如果@weekly_updates返回两个或更多相同的周数,我们应该得到最后一周的周数。查看示例。谢谢。
我改变了控制器中的方法。
@weekly_updates = current_user.user_updates.latest.offset(params[:offset] || 0).group_by {|u| u.week_number }.uniq
但它没有帮助。
控制器中的方法。
def all
@weekly_updates = current_user.user_updates.latest.offset(params[:offset] || 0)
end
计算周数的模型中的方法:
class UserUpdate < ActiveRecord::Base
def week_number
return 1 unless user.first_program_started_at.present?
(((created_at.utc) - user.first_program_started_at.utc.beginning_of_day) / 86400 / 7).ceil.to_i || 1
end
end
JSON:
json.weekly_updates @weekly_updates do |j1, weekly_update|
j1.week_number weekly_update.try(:week_number)
end
示例:
"weekly_updates":
[
{
"id":25392,
"created_at":"2014-03-21T10:13:54+04:00",
"week_number":2
}
,
{
"id":25393,
"created_at":"2014-03-20T23:59:59+04:00",
"week_number":2
}
{
"id":25394,
"created_at":"2014-03-26T23:59:59+04:00",
"week_number":3
}
]
应该得到这个。
"weekly_updates":
[
{
"id":25393,
"created_at":"2014-03-20T23:59:59+04:00",
"week_number":2
}
{
"id":25394,
"created_at":"2014-03-26T23:59:59+04:00",
"week_number":3
}
]