【发布时间】:2011-02-02 21:45:58
【问题描述】:
我的应用使用 :has_many :through 关联,我无法弄清楚如何最有效地加载和显示来自关联两端和关联本身的数据。
这是我的课程:
class Person < ActiveRecord::Base
has_many :people_ranks
has_many :ranks, :through => :people_ranks
has_many :institutions_people
has_many :institutions, :through => :institutions_people
belongs_to :school
belongs_to :department
end
class Institution < ActiveRecord::Base
has_many :institutions_people
has_many :people, :through => :institutions_people
end
class InstitutionsPerson < ActiveRecord::Base
belongs_to :institution
belongs_to :person
end
及其对应的型号:
create_table :people, :force => true do |t|
t.string :name
t.string :degree
t.integer :year_grad
t.integer :year_hired
end
create_table :institutions, :force => true do |t|
t.string :name
t.integer :ischool
end
create_table :institutions_people, :id => false do |t|
t.integer :institution_id
t.integer :person_id
t.string :rel_type
end
我想用@person.year_hired、@person.institution.name 和@person.institution.institutions_people.rel_type(其中rel_type 是“已毕业”或“已雇用:) 之类的内容显示一个人的机构信息,但是我知道第三部分不起作用。在 person_controller 的显示位中使用以下内容:
@person = Person.find(params[:id], :include => [:school, :department, :institutions_people, :people_ranks, {:institutions_people => :institution}, {:people_ranks => :rank}])
让我可以访问@person.institutions 和@person.institutions_people,但是如何将连接中的rel_type 属性连接到person-institutions 关系? (我来自 PHP,现在如何构建 SQL 并在那里循环,但 RoR 让我很难过。)
我在“急切加载”和“与 :has_many :through 的关联”下寻求帮助,但我得到了有关建立关联的答案。我的问题实际上是在关联数据存在后访问它。我的应用程序使用静态数据,我不担心更新、销毁或创建方法。感谢您的帮助!
【问题讨论】:
标签: ruby-on-rails associations eager-loading