2011-10-31 296 views
1

想象一下4款车型中的Rails 3.1嵌套属性在Rails的

class Student < ActiveRecord::Base 
    has_many :memberships 
    has_many :courses, :through => :memberships 
    has_many :tests, :through => :courses 
end 

class Membership < ActiveRecord::Base 
    belongs_to :student 
    belongs_to :course 
end 

class Course < ActiveRecod::Base 
    has_many :tests 
    has_many :students, :through => :memberships 
end 

class Test < ActiveRecord::Base 
    belongs_to :course 
end 

我怎么能输出排序列表的学生即将推出的测试 (按日期IE)(我猜有一个相当简单的答案,但我一直在努力白费了一会儿)

我最好的猜测是一样的东西:

@upcomingTests = @currstudent.tests.sort_by &:testDateTime 

,但它似乎返回一个空数组

+0

请张贴您的最佳尝试和结果。 –

回答

0

首先,您的模型“课程”存在轻微错误。它需要“belongs_to:student”。

class Course < ActiveRecod::Base 
    has_many :tests 
    has_many :students, :through => :memberships 
    belongs_to :student 
end 

你已经创建并填充一个外键后,您可以在测试模式创建一个简单的named_scope:

named_scope :ordered, :order => "created_at DESC" 

然后,它不管你想要的是访问它的只是事项:

@ordered_tests = @student.tests.ordered