【问题标题】:eager loading with attributes in join model rails急切加载连接模型导轨中的属性
【发布时间】: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


    【解决方案1】:

    访问数据的方式是通过机构_人协会。所以,你会做这样的事情:

    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 %>
    

    【讨论】:

    • 谢谢@Rick 我最终使用@rel_inst = @me.institutions_people 一次获得了许多机构。奇迹般有效。感谢您的帮助!
    猜你喜欢
    • 2016-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多