[英]Rails activerecord find objects with specific children associations
I have a model User who can have many Features: 我有一个可以具有许多功能的模型用户:
class User << ActiveRecord::Base
has_many :features, dependent: :destroy
end
class Feature << ActiveRecord::Base
belongs_to :user
# columns id, user_id, name
end
I have 2 features I can put on a user called "feat1" and "feat2" The 2 features can combine for a total of 4 types of users: 我有2个可以放置在名为“ feat1”和“ feat2”的用户上的功能。这2个功能可以组合为总共4种类型的用户:
I want to create scopes on user to scope out the 4 types of users. 我想在用户上创建范围,以将4种类型的用户划分为范围。
User.only_feat1
User.only_feat2
User.both_feats
User.no_feats
I've been playing around with .merge, .uniq, .joins, .includes, but can't seem to figure out the activerecord way. 我一直在玩.merge,.uniq,.joins,.includes,但似乎无法弄清楚activerecord的方式。
So here's my solution. 所以这是我的解决方案。 It involves a lot of raw SQL, but it gets the job done.
它涉及很多原始SQL,但可以完成工作。 The problem is if I join the same table (features) to my users table more then once, then the where clauses get overwritten and I can't do multiple joins.
问题是,如果我再一次将同一表(功能)连接到我的用户表,那么where子句将被覆盖,并且我无法进行多次连接。
So to combat this problem, I wrote a lot of raw sql which explicitly aliases the table on the join forcing the double join table. 因此,为了解决这个问题,我编写了很多原始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') }
Hope this helps anyone else. 希望这对其他人有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.