想象一下Rails 3.1中的4个模型
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
如何输出学生即将进行的测试的排序列表(即按日期) (我猜有一个相当简单的答案,但我一直试图徒劳无功)
我最好的猜测是:
@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