如何使用Rails的读取方法编写此SQL?

时间:2014-06-17 03:10:34

标签: sql ruby-on-rails ruby activerecord

我有以下设置:

question.rb

class Question < ActiveRecord::Base
    has_many :answers

    #validations, methods, etc
    ...

    #Returns the questions with the most answers
    def Question.top_questions(max = 10)
        sql = "SELECT question_id, COUNT('question_id') as aCount FROM answers GROUP BY question_id ORDER BY aCount DESC LIMIT #{max.to_i}" # Probably shouldn't use string interpolation here :D
        Question.connection.execute(sql)
    end
end

answer.rb

class Answer < ActiveRecord::Base
    belongs_to :question
    ...
end

如果我调用Question.top_questions(),那么它会返回:

  

[{&#34; question_id&#34; =&gt; 1,&#34; aCount&#34; =&gt; 25,0 =&gt; 1,1 =&gt; 25},{&#34; question_id& #34; =&gt; 38,&#34; aCount&#34; =&gt; 3,0 =&gt; 38,1 =&gt; 3},{&#34; question_id&#34; =&gt; 45,&# 34; aCount&#34; =&gt; 3,0 =&gt; 45,1 =&gt; 3},{&#34; question_id&#34; =&gt; 26,&#34; aCount&#34; =&gt; 2 ,0 =&gt; 26,1 =&gt; 2},{&#34; question_id&#34; =&gt; 46,&#34; aCount&#34; =&gt; 2,0 =&gt; 46,1 =&gt; ; 2},{&#34; question_id&#34; =&gt; 48,&#34; aCount&#34; =&gt; 2,0 =&gt; 48,1 =&gt; 2},{&#34; question_id& #34; =&gt; 51,&#34; aCount&#34; =&gt; 2,0 =&gt; 51,1 =&gt; 2},{&#34; question_id&#34; =&gt; 5,&# 34; aCount&#34; =&gt; 1,0 =&gt; 5,1 =&gt; 1},{&#34; question_id&#34; =&gt; 15,&#34; aCount&#34; =&gt; 1 ,0 =&gt; 15,1 =&gt; 1},{&#34; question_id&#34; =&gt; 20,&#34; aCount&#34; =&gt; 1,0 =&gt; 20,1 =&gt; ; 1}]

我不确定在保持代码清洁的同时如何使用视图中返回的数据。 所以我想知道我是否可以使用rails&#39;来编写Question.top_questions()方法。读取方法(find(),where()等)。或者我如何让它返回一个Question对象数组。

1 个答案:

答案 0 :(得分:0)

它返回一个哈希数组,您可以根据需要在视图中使用它。

但如果您不想编写本机sql,可以按如下所示重写它。

def self.top_questions(max = 10)
    Question.joins('LEFT JOIN answers ON questions.id = answers.question_id')
            .select('questions.*, count(answers.id) as answers_count')
            .group('questions.id')
            .order('answers_count desc')
            .limit(max)        
end