2016-06-07 2 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