活动记录has_many通过过滤

问题描述 投票:2回答:2

查询自定义组织类型用户体验的最佳方法是什么?换句话说,只检索某种类型组织的用户体验。

User
  has_many :organizations, through: :experience
end

Experience
  belongs_to :organization
  belongs_to :user
end

Organization
  has_many :users, through: :experience
end

我正在尝试执行以下操作:

User.first.public_experience 

这将检索公共类型组织中的所有用户体验

ruby-on-rails ruby-on-rails-4 rails-activerecord
2个回答
2
投票

您可以添加另一个仅限于特定类型组织的has_many关联。例如,如果您的组织有一个名为“public”的布尔变量,那么您可以添加:

class User < ActiveRecord::Base
  has_many :organizations, through: :experience
  has_many :public_organizations, -> { where public: true}, class_name: "Organization", through: :experience, source: :organization
end

class Experience < ActiveRecord::Base
  belongs_to :organization
  belongs_to :user
end

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

0
投票

最后这是我的解决方案,我已经通过体验模型加入了。

class User
    has_many :public_experience, -> { public_experience }, :class_name => 'Experience'
end

class Experience
  scope :public_experience, -> { joins(:organization).merge(Organization.publicly_related) }
end

class Organization
  scope :publicly_related, -> { where 'organization_types_id = ?', 1 }
end

这允许仅从公共组织获得经验

© www.soinside.com 2019 - 2024. All rights reserved.