Rails where() clause on model association?
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!
Solution 1:
Try this:
User.joins(:account).where(:accounts => { :active => true })
Solution 2:
You need to join the accounts table and merge appropriate Account scope:
User.joins(:account).merge(Account.where(:active => true))
Solution 3:
Use a where clause in the Account model's association:
class Account < ActiveRecord::Base
has_many :users, -> {where(active: true)}
The other queries will work, but if you only always care about active users, filtering at the association level will properly encapsulate the filter and save you headaches in the future.
Update:
You can also specify 2 relations on the same table:
class Account < ActiveRecord::Base
has_many :users
has_many :active_users, -> {where(active: true)}, :class_name => 'User'
2nd Update:
After re-reading the question, I now see that my answer didn't answer the question. Here's my answer to the question:
User.where(account: Account.where(active: true))
3rd Update: Here's an example User model that has an active_users attribute
class User < ActiveRecord::Base
belongs_to :account
def self.active
where(account: Account.where(active: true))
end
end
Doing it this way allows you to put it inline with other user queries:
User.active.where(created_at: (1.week.ago..0.day.ago)).count
Solution 4:
Try this:
Account.includes(:users).where(active: true)