我有以下型号:
class User < ActiveRecord::Base
has_many :results, :dependent => :destroy
has_many :participants, :dependent => :destroy
has_many :courses, :through => :participants
end
class Course < ActiveRecord::Base
has_many :tests, :dependent => :destroy
has_many :participants, :dependent => :destroy
has_many :users, :through => :participants
end
class Result < ActiveRecord::Base
belongs_to :test
belongs_to :user
end
class Test < ActiveRecord::Base
belongs_to :course
has_many :results, :dependent => :destroy
end
理念是用户 has_and_belongs_to_many 课程,课程 has_many 测试,以及每个测试 has_and_belongs_to_many 用户(结果)。 那么从单个课程(不是测试)中选择每个结果的最佳查询是什么,以及从单个课程中选择每个结果但是来自一个用户的查询。
谢谢!
答案 0 :(得分:2)
要从特定课程中获得结果 - 假设两者之间唯一的桥梁是测试模型,则需要在测试中包含测试。
Result.find(:all, :conditions => ["tests.course_id = ?",@course.id], :include => :test)
对于第二个查询:
Result.find(:all, :conditions => ["user_id = ? AND tests.course_id = ?",@user.id, @course.id], :include => :test)