繁体   English   中英

Rails ActiveRecord查找具有特定子关联的对象

[英]Rails activerecord find objects with specific children associations

我有一个可以具有许多功能的模型用户:

class User << ActiveRecord::Base
  has_many :features, dependent: :destroy
end

class Feature << ActiveRecord::Base
  belongs_to :user
  # columns id, user_id, name
end

我有2个可以放置在名为“ feat1”和“ feat2”的用户上的功能。这2个功能可以组合为总共4种类型的用户:

  1. 用户只有feat1
  2. 用户只有feat2
  3. 用户同时具有feat1和feat2
  4. 用户具有NEITHER feat1和feat2

我想在用户上创建范围,以将4种类型的用户划分为范围。

User.only_feat1
User.only_feat2
User.both_feats
User.no_feats

我一直在玩.merge,.uniq,.joins,.includes,但似乎无法弄清楚activerecord的方式。

所以这是我的解决方案。 它涉及很多原始SQL,但可以完成工作。 问题是,如果我再一次将同一表(功能)连接到我的用户表,那么where子句将被覆盖,并且我无法进行多次连接。

因此,为了解决这个问题,我编写了很多原始sql,它们在联接上强制为双联接表显式地别名表。

scope :without_feature, ->(feat) { joins("LEFT OUTER JOIN features af ON users.id = af.user_id AND af.name = '#{feat}'").where(af: {id: nil}) }
scope :feat1, -> { joins("INNER JOIN features rs ON users.id = rs.user_id AND rs.name = 'feat1'") }
scope :feat2, -> { joins("INNER JOIN features rr ON users.id = rr.user_id AND rr.name = 'feat2'") }
scope :both_feats, -> { feat1.feat2 }
scope :only_feat1, -> { feat1.without_feature('feat2') }
scope :only_feat2, -> { feat2.without_feature('feat1') }

希望这对其他人有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM