I have two models User
and Subscription
as follows
class User < ApplicationRecord
has_many :subscriptions
end
class Subscription < ApplicationRecord
belongs_to :user
# attributes
# name string
# premium boolean
# ...
end
Users will be having many subscription. How Can I find all the users who does not have a premium subscription (premium =true)
User.where('id not in (select user_id from subscriptions where premium = true)')
. This works for me with subquery. Is there a better way of doing the same with joins?
2
Answers
As @The russian shame said your query perfomance is good enough
I just add another query with
EXISTS
to compareYou can use
where_exists
gem for this purpose asYou’re better using the query you currently have.
Take a look at two other different ways to achieve what you need, their execution time is slightly different (there are many other ways to get this done, but I got no time);