通过ActiveRecord中的DB访问获取关联对象

时间:2014-04-02 21:00:38

标签: ruby-on-rails ruby activerecord ruby-on-rails-4

我有3个模特:卫报,学生和组织。 Guardian通过链接模型连接到Student,类似地,Student通过链接模型连接到Organization。我需要为每个监护人,一系列(不同的)组织提供帮助,并且我想知道最好的方法是什么。

目前我在Guardian类的应用程序级别执行此操作

def organizations
  orgs = []
  students.each do |s|
    s.organizations.each do |o|
      orgs << o if !orgs.include?(o)
    end
  end
  orgs
end

我想知道是否有更好的方法来做到这一点,最好是在数据库级别。任何帮助将不胜感激。

编辑:这里有我的模型的更详细描述

class Person < ActiveRecord::Base
end 

class Guardian < Person
  has_many :student_guardian_links, inverse_of: :guardian, dependent: :destroy
  has_many :students, through: :student_guardian_links, inverse_of: :guardians
end

class Student < Person
  has_many :student_guardian_links, inverse_of: :student, dependent: :destroy
  has_many :guardians, through: :student_guardian_links, inverse_of: :students
  has_many :student_organization_links, inverse_of: :student, dependent: :destroy
  has_many :organizations, through: :student_organization_links
end

class Organization < ActiveRecord::Base
  has_many :student_organization_links, inverse_of: :organization, dependent: :destroy
  has_many :students, through: :student_organization_links, inverse_of: :organizations
end

3 个答案:

答案 0 :(得分:0)

这应该有效:

students.map { |student| student.orgs }.flatten.uniq

你采取的方法实际上是一样的。只是使用更实用的方法。

答案 1 :(得分:0)

通过关系数据库,通常可以从目标集中进行思考。因此,您希望组织具有特定条件(他们让学生与特定监护人联系)

在ActiveRecord中,我们有joins。它是一个错误名称,因为您仍然只获得组织对象,它只使用SQL连接从数据库中获取它们,并且您可以在连接对象上指定条件。

在“加入嵌套关联”和“在连接表上指定条件”中查看http://guides.rubyonrails.org/active_record_querying.html

因此,根据您的确切模型(请记住您需要向后连接),它可能如下所示:

Organinisation.joins(:students).where('student.guardian_id' => mygivenguardian.id).distinct()
当联接可以导致行的倍增时,

distinct很重要,例如当监护人与多个学生连接到组织时。

答案 2 :(得分:0)

试试这个:

class Guardian < ActiveRecord::Base
  has_many :organizations,
           :through => :students
  # Your existing relationships go here
end

通过这种方式,您只需调用guardian.organizations.uniq即可获取与特定Guardian对象关联的不同组织的列表。

相关问题