查询自定义组织类型用户体验的最佳方法是什么?换句话说,只检索某种类型组织的用户体验。
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
这将检索公共类型
组织中的所有用户体验答案 0 :(得分: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
答案 1 :(得分: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
这允许仅从公共组织获得经验