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

Ruby on rails 通过ActiveRecord中的DB访问获取关联对象,ruby-on-rails,ruby,activerecord,ruby-on-rails-4,Ruby On Rails,Ruby,Activerecord,Ruby On Rails 4,我有三种模式:监护人、学生和组织。监护人通过链接模型连接到学生,同样,学生通过链接模型连接到组织。我需要为每一位卫报获得一份(不同的)组织的名单,我想知道这样做的最佳方式是什么 目前我在Guardian类的应用程序级别上做这件事 def organizations orgs = [] students.each do |s| s.organizations.each do |o| orgs << o if !orgs.include?(o) end

我有三种模式:监护人、学生和组织。监护人通过链接模型连接到学生,同样,学生通过链接模型连接到组织。我需要为每一位卫报获得一份(不同的)组织的名单,我想知道这样做的最佳方式是什么

目前我在Guardian类的应用程序级别上做这件事

def organizations
  orgs = []
  students.each do |s|
    s.organizations.each do |o|
      orgs << o if !orgs.include?(o)
    end
  end
  orgs
end
def组织
orgs=[]
学生们,每个人都做|
s、 组织。每个组织都有|
组织这应该有效:

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

这和你现在采取的方法是一样的。仅使用功能更强大的方法。

处理关系数据库通常最好从目标集进行思考。因此,你需要具备特定条件的组织(他们让学生与特定监护人建立联系)

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

请看“连接嵌套关联”和“在连接的表上指定条件”

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

Organinisation.joins(:students).where('student.guardian_id' => mygivenguardian.id).distinct()
distinct
在连接可能导致行的乘法时非常重要,例如监护人与多个学生连接到组织时。

尝试以下方法:

class Guardian < ActiveRecord::Base
  has_many :organizations,
           :through => :students
  # Your existing relationships go here
end
class-Guardian:学生
#你现有的关系就在这里
结束

这样,您只需调用
guardian.organizations.uniq
即可获得与特定guardian对象关联的不同组织的列表。

如果您只需更明确地发布模型之间的关系,例如:guardian has\u many:link\u model;卫报:学生,通过::link\u model谢谢你的提示。刚刚加进去的。嘿,谢谢。我尝试了--Organization.joins(:students).where('people.guardian_id'=>158850).distinct(),但它给了我一个错误ActiveRecord::StatementInvalid:PG::UndefinedColumn:error:列people.guardian_id不存在。(people是学生和监护人的名字,我认为这是一个自联接,所以会出错)。不确定如何重建查询。感谢您的帮助!
class Guardian < ActiveRecord::Base
  has_many :organizations,
           :through => :students
  # Your existing relationships go here
end