Rails where() clause on model association?

Viewed 40874

Suppose I have an Account model which has_many Users. Accounts have a boolean "active" column. How can I get all Users that belong to "active" accounts?

@users_of_active_accounts = User.?

Thanks!

5 Answers

Try this:

Account.includes(:users).where(active: true)

A gem that exists to do that: activerecord_where_assoc (I'm the author)

With it, you can do what you want this way:

@users_of_active_accounts = User.where_assoc_exists(:account, active: true)

And if you have a scope on Account for active, you could call it this way:

@users_of_active_accounts = User.where_assoc_exists(:account, &:active)

So now, if you want, you can make a nice scope for this:

class User < ActiveRecord::Base
  belongs_to :account

  scope :active_account, -> { where_assoc_exists(:account, active: true) }
end

@users_of_active_accounts = User.active_account

Read more in the documentation. Here is an introduction and examples.

Related