我有两个模型的问题和答案。和一个问题has_many答案。 我怎样才能找到所有没有答案的问题?
答案 0 :(得分:5)
我建议将:counter_cache
添加到Answer
模型中。然后你可以在Question
模型
class Question < ActiveRecord::Base
has_many :answers
named_scope :unanswered, :conditions => {:answers_count => 0}
end
Answer
模型看起来像这样
class Answer < ActiveRecord::Base
belongs_to :question, :counter_cache => true
end
答案 1 :(得分:2)
class Question < ActiveRecord::Base
has_many :answers
def self.unanswered
find_by_sql("select * from questions where id not in (select DISTINCT question_id from answers) ORDER BY updated_at DESC")
end
end
class Answer < ActiveRecord::Base
belongs_to :question
end
在控制器中
@unanswered= Question.unanswered
FOR PAGINATION
def self.unanswered
find_by_sql("select * from questions where id not in (select DISTINCT question_id from answers) ORDER BY updated_at DESC")
end
@unanswered= Question.unanswered
@unanswered.paginate(:page => params[:page], :per_page => 10)
因为这会获取所有的recors然后使用分页试试
def self.unanswered(page_no=1, per_page=10)
find_by_sql("select * from questions where id not in (select DISTINCT question_id from answers) ORDER BY updated_at DESC").paginate(:page => page_no, :per_page => per_page)
end
@unanswered= Question.unanswered(params[:page], params[:per_page])
答案 2 :(得分:1)
如果您要采用Salil所描述的直接SQL方法而不是Eimantas建议的更多ActiveRecord方法,那么您可能希望使用以下SQL
SELECT * FROM questions as q
WHERE NOT EXISTS (SELECT * FROM answers AS a WHERE a.question_id = q.id)
与
相反select * from questions
where id not in (select DISTINCT question_id from answers)
在140000行的表中,前一个查询对我的执行速度提高了8倍,其中10%的行没有应答。我预计这将因发动机而异,取决于未回答问题的百分比。
如果你在问题表上创建一个名为answers_count的列,那么Eimantas解决方案很不错,那么ActiveRecord会为你保留这个,而且应该非常快。