我有一个可以拥有许多功能的模型用户:
class User << ActiveRecord::Base
has_many :features, dependent: :destroy
end
class Feature << ActiveRecord::Base
belongs_to :user
# columns id, user_id, name
end
我有两个功能可以放在一个名为&#34; feat1&#34;和#34; feat2&#34;这两个功能可以合并为4种类型的用户:
我想在用户上创建范围,以确定4种用户的范围。
User.only_feat1
User.only_feat2
User.both_feats
User.no_feats
我一直在玩.merge,.uniq,.joins,.includes,但似乎无法找出主动记录方式。
答案 0 :(得分:0)
所以这是我的解决方案。它涉及大量原始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') }
希望这有助于其他任何人。