2014-06-17 52 views
0

我有以下設置:如何使用Rails的讀取方法編寫這個SQL?

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(),然後返回此:

[{ 「question_id」=> 1 「aCount」=> 25,0 => 1,1 => 25},{ 「question_id」=> 38, 「aCount」=> 3,0 => 38, 1 => 3},{「問題_id 「=> 45, 」aCount「=> 3,0 => 45,1 => 3},{」 question_id「=> 26, 」aCount「=> 2,0 => 26,1 => 2}, {「question_id」=> 46,「aCount」=> 2,0 => 46,1 => 2},{「question_id」=> 48,「aCount」=> 2,0 => 48,1 => 2 },{「question_id」=> 51,「aCount」=> 2,0 => 51,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}]

我不知道如何使用視圖中返回的數據,同時仍保持代碼清潔。 所以我想知道如果我能寫Question.top_questions()使用方法Rails的讀取方法(找到(),其中(),等)。或者我怎樣才能讓它返回一個Question對象數組。

回答

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 
+0

感謝的人!很棒! – Xerif917