Rails: Getting all has_many objects associated with an active relation of parents

1.4k Views Asked by At

I have what I suspect is a basic question. In my rails app, One user has many scores. Is there a way to get all the scores of an active relation of users. I can do user.scores (obviously) but if users is a group of users I need to do something like users.scores. This is clearly not correct.

2

There are 2 best solutions below

0
mikdiet On BEST ANSWER

You can use

Score.where(user: users)

This will construct sql like

select * from scores where user_id in (select *.id from users where ..) 
4
Dharam Gollapudi On

Did you try the following?

@users.collect(&:scores).flatten!