如何根据喜欢的数量对用户的答案进行排序?

时间:2016-11-13 18:20:02

标签: ruby-on-rails

我想迭代所有用户的答案并按照收到答案的数量订购,但我无法弄清楚如何做到这一点,@ user.answers.likes不起作用,我找到了办法找到所有喜欢的用户的答案,但这不是我想要做的。谢谢你的帮助。

模型/ answer.rb

class Answer < ApplicationRecord
belongs_to :question
belongs_to :user
has_many :likes, dependent: :destroy

模型/ user.rb

class User < ApplicationRecord
has_many :answers
has_many :likes

模型/ like.rb

class Like < ApplicationRecord
belongs_to :user
belongs_to :answer

schema.rb

create_table "answers", force: :cascade do |t|
 t.text     "content"
 t.datetime "created_at",                  null: false
 t.datetime "updated_at",                  null: false
 t.integer  "question_id"
 t.integer  "user_id"
 t.boolean  "accepted",    default: false
 t.index ["question_id"], name: "index_answers_on_question_id"
end

create_table "likes", force: :cascade do |t|
 t.integer  "user_id"
 t.integer  "answer_id"
 t.datetime "created_at", null: false
 t.datetime "updated_at", null: false
end

2 个答案:

答案 0 :(得分:1)

这样的东西应该在纯SQL中工作。

sql = "SELECT * FROM answers INNER JOIN likes ON answers.id = likes.answer_id WHERE COUNT(likes.id) > 0 AND answers.user_id = #{@user.id}  GROUP BY answers.id ORDER BY COUNT(likes.id)"

records_array = ActiveRecord::Base.connection.execute(sql)

答案 1 :(得分:1)

@user.answers.joins(:likes)
    .select('answers.*, COUNT(likes.id) as likes_count')
    .group('answers.id')
    .order('likes_count DESC')

如果您只想选择喜欢的答案,可以添加 条件

@user.answers.joins(:likes)
    .select('answers.*, COUNT(likes.id) as likes_count')
    .group('answers.id')
    .having('COUNT(likes.id) > 0')
    .order('likes_count DESC')