Delos Chang
Delos Chang

Reputation: 1853

Rails find using where in one to many relation

I have a User model that has many "states":

class User
    has_many states

class State
    belongs_to user

Now, I'd like to go through each User and find all the Users with that state something like...

state = State.last
# I want to get all the users where state appears in ANY user's user.states

User.where(state IN user.states.. ) 

Any advice would be appreciated!

Upvotes: 1

Views: 914

Answers (1)

Gavin Miller
Gavin Miller

Reputation: 43815

One way is to use a join to get the user's that have the state:

User.joins(:states).where(state: 'some_type_of_state')

The other way is by grabbing all the user id's that have the specific state, and then querying for those users:

user_ids = State.where(state: 'some_type_of_state').pluck(:user_id)
users = User.where(id: user_ids)

The last query typically doesn't perform as well.

Upvotes: 2

Related Questions