【问题标题】:Find all the users in an organization and it's suborganizations查找组织及其子组织中的所有用户
【发布时间】:2016-03-01 18:00:51
【问题描述】:

一个用户属于一个组织,而该组织又可以有多个用户和子组织。您如何找到所有组织的用户?

我有名为UserOrganization 的模型。它们有以下关系:

在用户模型中:

belongs_to :organization

在组织模型中:

has_many :users
has_many :child_organizations, class_name: "Organization", foreign_key:"parent_id"
belongs_to :parent, class_name: "Organization"

我要查找属于当前用户组织child_organizations的所有用户。

@users = current_user.organization.child_organizations.users

它返回此错误:

undefined method `users' for Organization::ActiveRecord_Associations_CollectionProxy:0x8f975d0

【问题讨论】:

  • 您应该编辑您的问题并根据模型发布一些示例数据

标签: ruby-on-rails activerecord associations


【解决方案1】:

根据您的问题的格式,我不完全确定您对模型关系有什么影响。但是如果你想找到所有属于 current_user 组织的 child_organizations 的用户...

这是您建立关系的方式

class User < ActiveRecord::Base
  belongs_to :organization
  belongs_to :child_organization
end

class Organization < ActiveRecord::Base
  has_many :child_organizations
  has_many :users, through: :child_organizations
end

class ChildOrganization < ActiveRecord::Base
  belongs_to :organization
  has_many :users
end

现在您可以使用以下内容了

@users = current_user.organization.users

【讨论】:

  • 谢谢,这意味着我需要另一个存储 child_organization 用户的模式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-06
  • 1970-01-01
  • 2023-04-06
  • 1970-01-01
  • 1970-01-01
  • 2019-05-14
  • 1970-01-01
相关资源
最近更新 更多