1

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.

Dharam Gollapudi
  • 6,328
  • 2
  • 34
  • 42
GhostRider
  • 2,109
  • 7
  • 35
  • 53

2 Answers2

2

You can use

Score.where(user: users)

This will construct sql like

select * from scores where user_id in (select *.id from users where ..) 
mikdiet
  • 9,859
  • 8
  • 59
  • 68
0

Did you try the following?

@users.collect(&:scores).flatten!
Dharam Gollapudi
  • 6,328
  • 2
  • 34
  • 42
  • I think the accepted answer is more efficient. Correct me if I am wrong – GhostRider Sep 12 '16 at 17:07
  • Both will produce the same underlying `sql`. Which one to use depends upon your scenario and other context. Either way, I would move this logic to the model for testability and maintenance. – Dharam Gollapudi Sep 12 '16 at 17:14
  • You are not right @Dharam, your code produces N+1 queries. But it could be improved using `includes`: `@users.includes(:scores).collect(&:scores).flatten!` - this will be only 2 queries. – mikdiet Sep 12 '16 at 19:13
  • Good call @MikDiet, didn't realize that. – Dharam Gollapudi Sep 12 '16 at 19:16