如何在Rails中查询2个不同的表?

时间:2014-06-25 17:30:02

标签: ruby-on-rails activerecord

class Answer < ActiveRecord::Base
  attr_accessible :question_id, :result, :user_id
end

class Question < ActiveRecord::Base
  attr_accessible :prompt, :topic
end

我的Rails应用程序中有以下2个模型。我想运行一个查询,选择具有特定主题(数学)的问题但是对于给定的user_id没有答案(结果=&#34;未答复&#34;)。

我无法提出可以获得此问题的查询。

first_question = Question.where(:topic => "Math")

但我不确定如何合并:result => "Unanswered"表中的Answer。有什么建议吗?

2 个答案:

答案 0 :(得分:2)

要获得MATH主题下用户#1的所有未回答的问题,请使用:

Question.includes(:answers).where(:topic => 'MATH', 'answers.result' => 'Unanswered', 'answers.user_id' => 1)

如果您想获得第一个未回答的问题:

Question.includes(:answers).where(:topic => 'MATH', 'answers.result' => 'Unanswered', 'answers.user_id' => 1).first

我可能会创建一些范围以使这些更容易重用:

class Question < ActiveRecord::Base
  has_many :answers

  scope :topic, lambda {|topic|
    where(:topic => topic)
  }

  scope :unanswered_by, lambda { |user|
    includes(:answers).where('answers.result' => 'Unanswered', 'answers.user_id' => user.id)
  }

end

所以你可以这样查询:

user = User.last
Question.topic('MATH').unanswered_by(user)

答案 1 :(得分:1)

您可以使用joinsquestionsanswers表格之间进行内部联接,然后merge查询:result => "Unanswered"

Question.joins(:answer).where(:topic => "Math", :user_id => <user_id>).merge(Answer.where(:result => "Unanswered"))