我正在构建一个Rails 5.0应用程序。
在这个应用程序中,我有三个模型,用户,反馈和分配。
当用户将一个或多个接收者添加到他或她创建的Feedback对象时,会创建一个分配以保持此连接。
用户
User(id: integer, account_id: integer, fullname:string)
反馈
Feedback(id: integer, account_id: integer, user_id: integer, title: string, ftype: string, badge: string, category: string, privacy: string, anonymous: boolean, description: text, created_at: datetime, updated_at: datetime)
create_table "feedbacks", force: :cascade do |t|
t.integer "account_id"
t.integer "user_id"
t.string "title"
t.string "ftype", default: "provided"
t.string "badge"
t.string "category"
t.string "privacy"
t.boolean "anonymous", default: false
t.text "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["account_id"], name: "index_feedbacks_on_account_id", using: :btree
t.index ["user_id"], name: "index_feedbacks_on_user_id", using: :btree
end
分配
Assignment(id: integer, account_id: integer, user_id: integer, assignable_type: string, assignable_id: integer, created_at: datetime, updated_at: datetime)
create_table "assignments", force: :cascade do |t|
t.integer "account_id"
t.integer "user_id"
t.string "assignable_type"
t.integer "assignable_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["account_id"], name: "index_assignments_on_account_id", using: :btree
t.index ["assignable_type", "assignable_id"], name: "index_assignments_on_assignable_type_and_assignable_id", using: :btree
t.index ["user_id"], name: "index_assignments_on_user_id", using: :btree
end
如何获得反馈的前五位接收者?
答案 0 :(得分:1)
您可以尝试定义每个用户拥有的分配数量:
Assignment.group(:user_id).count
它将返回哈希{1 => "10", 2 => "15", ...}
然后对它进行排序并提取前5个元素。
ids = Assignment.group(:user_id).count.sort_by{|_, v| -v}.first(5).map{|id, _| id}
它会返回适当用户的ID。
然后只需按ID找到用户。
users = User.where(id: ids)