我正在尝试做一个 feed(每天按照 feed 的时间线)
我有一个表photos
,它存储用户上传的照片,一个表follows
,它存储每个用户关注的用户。
create_table "photos", force: :cascade do |t|
...
t.integer "user_id"
t.datetime "created_at"
t.datetime "updated_at"
...
create_table "follows", force: :cascade do |t|
t.integer "followable_id", null: false
t.string "followable_type", null: false
t.integer "follower_id", null: false
t.string "follower_type", null: false
...
t.datetime "created_at"
t.datetime "updated_at"
end
基本上,我想完成一个看起来像这样的提要(绘制比解释更容易)
- 最近出现在顶部
- 将我们“关注”的用户上传的所有照片(包括我自己的照片)分组为“一天”
- 显示今天、昨天、2天前等
最佳答案
这是一种解决方案。
current_user_id = current_user.id
Photo.select(%q{
user_id,
COUNT(*) no_photos,
date_trunc('day', created_at::timestamp) as what_day
}).group("what_day, user_id").order("what_day DESC").where(%Q{
user_id IN (
(SELECT followable_id FROM follows where follower_id = #{current_user_id})
UNION ALL
(SELECT #{current_user_id} as followable_id)
)
})
date_trunc
将日期截断到指定的精度,在本例中是一天的开始。我不确定 follows.followable_type
在你的情况下做了什么,但以上应该有效。
关于sql - 创建按天分组的提要(以下)和最近在 ruby on rails 上订购的用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33820824/