user2320239
user2320239

Reputation: 1038

Get records based on associations attributes

I'm working on a project where I have a User, a user has one UserSetting. I want to get the users where User.user_setting.status == 'active'. I have at the moment:

User.joins(:user_setting).where(:user_setting => {:status => 'active'})

but it doesn't seem to work, I get the error

Unknown column 'user_setting.status' in 'where clause'

If anyone could help me with where I'm going wrong that would be greatly appreciated.

Upvotes: 0

Views: 52

Answers (1)

Andrey Deineko
Andrey Deineko

Reputation: 52357

User.joins(:user_setting).where(user_settings: { status: 'active' })

In joins you should use the association name, whereas in the where clause you should use the database table name (which is user_settings, not user_setting).

edit

To not receive duplicate entries in the resulting collection you could use GROUP BY clause:

User.joins(:user_setting)
    .where(user_settings: { status: 'active' })
    .group('users.id')

Another option would be using includes instead of joins:

User.includes(:user_setting)
    .where.not(user_settings: { id: nil })
    .where(user_settings: { status: 'active' })

Upvotes: 1

Related Questions