2011-10-31 198 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