【问题标题】:Active record has_many through filtering活动记录 has_man 通过过滤
【发布时间】:2015-09-01 12:29:19
【问题描述】:

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

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


    【解决方案1】:

    您可以添加另一个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
    

    【讨论】:

    • 关系的语法似乎有问题:“语法错误,意外'\n',期待=>”
    • 非常抱歉,我的错误。我现在已经编辑了我的原始答案,我希望它现在可以工作。
    • 该代码有效并且非常接近我的需求,过滤工作正常,但我仍然想要经验而不是组织返回。
    • 只是为了澄清一下:您在组织表中存储了一个布尔“公共”变量,然后想要查找用户对该变量设置为 true 的组织的所有体验?还是您将布尔值保存在经验表中?
    • 布尔值在组织表中,附加到不在经验中的组织模型。
    【解决方案2】:

    最后这是我的解决方案,我通过体验模型做了一个join。

    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
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-03
      相关资源
      最近更新 更多