Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/unity3d/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Rails的读取方法编写此SQL?_Sql_Ruby On Rails_Ruby_Activerecord - Fatal编程技术网

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

如何使用Rails的读取方法编写此SQL?,sql,ruby-on-rails,ruby,activerecord,Sql,Ruby On Rails,Ruby,Activerecord,我有以下设置: 问题.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('qu

我有以下设置:

问题.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
答案.rb

class Answer < ActiveRecord::Base
    belongs_to :question
    ...
end
如果我调用Question.top_questions,它会返回以下内容:

1.25,0=>1,1.1=>1,1.1=>25},{1.0{1.0.0.0.1,1.0=>3,0.0=>38,0.0=>38,1.1,1.1,1.0=>1,1.1,1.1,1.1,1,1,1.5},{1,1.1,1,1,1.1,1,1,1.1,1,1},{1,1,1,1,1,1,1,1,1,1,1,1.1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0 0 0 0 0 0 0 0 0 0 0 0 0,0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1=>2},{question_id=>5,aCount=>1,0=>5,1=>1},{question_id=>15,aCount=>1,0=>15,1=>1},{question_id=>20,aCount=>1,0=>20,1=>1}]

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

它返回一个哈希数组,您可以在视图中随意使用它

但如果您不想编写本机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