2016-06-07 31 views
0
class Chapter < ApplicationRecord 
    has_many :courses 
end 

class Course < ApplicationRecord 
    belongs_to: chapter 
    has_many :modules 
end 

class Moudule < ApplicationRecord 
    belongs_to: course 
end 

我想章的模塊如何獲得孫子的ActiveRecord對象

我寫的代碼。

module_list = [] 
chapter = Chapter.find(1) 
chapter.courses.each |course| do 
    course.modules.each |module| do 
    module_list.push(module) 
    end 
end 

module_list 

但它並不聰明。

  • 許多每個巢。
  • module_list不是ActiveRecordObject。

有沒有好的方法?

回答

4

這是什麼 「到」 聯想是:

class Chapter < ApplicationRecord 
    has_many :courses 
    has_many :modules, :through => :courses 
end 

chapter = Chapter.find(1) 
chapter.modules