[英]How to get Grandson ActiveRecord Object
class Chapter < ApplicationRecord
has_many :courses
end
class Course < ApplicationRecord
belongs_to: chapter
has_many :modules
end
class Moudule < ApplicationRecord
belongs_to: course
end
我想獲取Chapter的模塊
我寫一個代碼。
module_list = []
chapter = Chapter.find(1)
chapter.courses.each |course| do
course.modules.each |module| do
module_list.push(module)
end
end
module_list
但這並不聰明。
有沒有好的方法?
這就是“直通”關聯的用途:
class Chapter < ApplicationRecord
has_many :courses
has_many :modules, :through => :courses
end
chapter = Chapter.find(1)
chapter.modules
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.