在rails中有很多关系帮助

时间:2010-06-04 09:52:40

标签: ruby-on-rails activerecord

我有两个模型的问题和答案。和一个问题has_many答案。 我怎样才能找到所有没有答案的问题?

3 个答案:

答案 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会为你保留这个,而且应该非常快。