通过关联访问记录数组

时间:2015-01-19 12:07:47

标签: ruby-on-rails ruby-on-rails-4

我有以下型号:

class User < ActiveRecord::Base
  has_many :questions
  has_many :answers

class Question < ActiveRecord::Base
  belongs_to :user
  has_many :answers

class Answer < ActiveRecord::Base
  belongs_to :user
  belongs_to :question

我想访问用户回答的问题。 我可以这样做:

question_ids = []
@user.answers.each do |answer|
  question_ids << answer.question.id
end
Question.where(id: question_ids)

有更好的方法吗?

2 个答案:

答案 0 :(得分:1)

您可以使用joins,如下所示:

Question.joins(:answers).where(answers: {user_id: @user.id})

答案 1 :(得分:1)

另一个选择是使用pluck,以避免在内存中加载所有答案对象:

Question.where(id: @user.answers.pluck(:question_id))