【发布时间】:2019-11-06 05:58:21
【问题描述】:
我想获取前 10 名选民的评论并添加分组依据?
示例响应:
1 => [1,2,3,4,5,6,7,8,9,10],
2 => [1,2,3,4]}
投票人数不得超过 10 人。
create_table "votes", force: :cascade do |t|
t.integer "user_id", limit: 4, null: false
t.integer "votable_id", limit: 4, null: false
t.string "votable_type", limit: 191, null: false
t.integer "weight", limit: 4
end
create_table "comments", force: :cascade do |t|
t.text "message", limit: 16777215, null: false
t.string "type", limit: 255
t.integer "commentable_id", limit: 4
t.string "commentable_type", limit: 191
t.integer "user_id", limit: 4, null: false
end
这是我的查询,它返回所有选民。相反,我需要为每条评论返回前 10 名选民。
Vote.where(votable_id: @comments_ids, votable_type: 'Comment').select(:votable_id, :user_id).group_by(&:votable_id)
【问题讨论】:
-
可以添加模型(投票、评论)和架构文件吗?
-
@SebastianPalma 已添加。
-
@sureshprasanna70 它增加了完成查询的限制,而不是我需要按数组单独分组。
-
由于您需要按数组限制单个组,我认为您应该尝试在单个模型中使用范围?
标签: mysql sql ruby-on-rails activerecord group-by