Search code examples
ruby-on-railsruby-on-rails-5

How to construct a query that checks if relation exists


I am building an Rails 5 app. In this app I got a User model and a Subscription model. I want to be able to get all Users that got an active Subscription.

User

has_one :subscription

- id,
- name
- email

Subscription

belongs_to :user

- id
- user_id
- title
- active (boolean)

I need to be able to do a query like this (below). In other words I need to find all Users that not only got a subscription but also where the active attribute is set to true.

User.with_active_subscriptions

I think I perhaps need to do a Scope but have no idea how to do it.


Solution

  • It's quite easy, actually, all you need to do is to use joins:

    scope :with_active_subscriptions, lambda {
      joins(:subscription).where(subscriptions: { active: true })
    }