2011-02-02 63 views
1

我的应用程序使用:has_many:通过关联,我无法弄清楚如何最有效地加载和显示关联两端的数据和关联本身。渴望加载属性加入模型轨道

这里是我的课:

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的show位中使用以下内容:

@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属性连接到人 - 机构关系? (我来自PHP,现在如何构建SQL并通过它循环,但RoR让我难住。)

我在“急切加载”和“与:has_many:通过关联寻找帮助“,但我得到关于建立协会的答案。我的问题实际上是在关联数据存在后访问关联数据。我的应用使用静态数据,我并不担心更新,销毁或创建方法。感谢您的帮助!

回答

0

访问数据的方式是通过institutions_people关联。所以,你会做这样的事情:

me = Person.first 
rel = me.institutions_people.first 

然后在视图

<%= rel.rel_type %> from <%= rel.institution.name %> 

或者,你可以给自己机构的完整列表,与他们的信息一起:

me = Person.first 

然后在视图中:

<% for ip in me.institutions_people %> 
    <%= ip.rel_type %> from <%= ip.institution.name %> 
<% end %> 
+0

Thanks @Rick我最终使用@rel_inst = @ me.institutions_people立即获得了许多机构。奇迹般有效。我感谢您的帮助! – Libby 2011-02-08 21:28:57