【问题标题】:Rails nested relationships in ActiveRecordActiveRecord 中的 Rails 嵌套关系
【发布时间】:2013-03-04 18:45:15
【问题描述】:
我想查询属于这些模型的学校的部分:
School
has_many :terms
Term
belongs_to :school
has_many :departments
Department
belongs_to :term
has_many :courses
Courses
belongs_to :department
has_many :sections
Section
belongs_to :course
我有点不知道该怎么做。
我希望能够调用属于学校的部分列表并从部分中找到学校(并查询它们之间的所有关系)
任何帮助将不胜感激。
【问题讨论】:
标签:
sql
ruby-on-rails
ruby-on-rails-3
activerecord
rails-activerecord
【解决方案1】:
必须从上到下遍历每个模型。
例如:
s = School.find(1)
s.terms.find(1).departments.find(1).courses.find(1).sections
这将为您提供与school_id = 1 关联的部分
由于您的模型有很多级联,除非您想更改数据库架构,否则您必须这样做。..
【解决方案2】:
如果您使用的是 Rails 3.1 或更高版本,您可以使用 :has_many :through 来帮助您获取每个学校内的部分。首先,您需要在模型中设置关系:
School
has_many :terms
has_many :departments, :through => :terms
Term
belongs_to :school
has_many :departments
Department
belongs_to :term
has_many :courses
has_many :sections, :through => :courses
Courses
belongs_to :department
has_many :sections
Section
belongs_to :course
那么要获得学校的部分,您可以做...
School.first.departments.collect{|d| d.sections}.flatten!
要获得某个部门所属的学校,您需要做的就是
section.course.department.term.school
【解决方案3】:
要从一个部分中找到学校,您只需:
section.course.department.term.school
如果没有太多记录可以减慢速度,您可以通过以下方式获取给定学校的一组部分:
sections = []
school.terms.each do |term|
term.departments.each do |department|
department.courses.each do |course|
course.sections.each do |section|
sections << section
end
end
end
end
如果您需要进行任何进一步的处理,这也将使您能够访问中间的每个关系。
这是一个更简洁的版本:
sections = school.terms.map(&:departments).flatten.map(&:courses).flatten.map(&:sections).flatten