获取模型以及相应的连接模型属性

时间:2011-12-16 10:44:52

标签: ruby-on-rails activerecord has-many-through

我有模特:

class Exam < AR::Base
  has_many :questions_in_exams
  has_many :questions, :through => :questions_in_exams
end

class QuestionsInExam < AR::Base
  belongs_to :examination
  belongs_to :question
  # This model also has a "question_index" attribute
end

class Question < AR::Base
  has_many :questions_in_exams
  has_many :examinations, :through => :questions_in_exams
end

考虑到考试的实例,我想要获取所有这些问题以及额外的问题 连接模型中的属性(如“question_index”)。我怎样才能做到这一点?

如果我这样做:

e = Examination.find(1)
questions = e.questions

然后,问题数组中的元素将不具有“question_index”属性

我想我可以写:

e = Examination.find(1)
questions = e.questions_in_exam(:include => "question")

但这似乎并不那么优雅,因为我需要的大多数数据都是在问题模型上, 但返回的数组将包含QuestionInExam实例。

有什么想法吗?

由于

1 个答案:

答案 0 :(得分:0)

从问题模型开始,类似这样

Question.select("questions.*, examination.id")
        .joins(:questions_in_exam => :examination)
        .where("examinations.id=?", 1) 

# Note that inside "select" you can specified all the attributes you want from any of the joined models.

如果您对查询感到满意,请将其转换为scope

并且您的最终通话可能如下所示:Question.for_exam(1)