Guest User

Untitled

a guest
Jul 22nd, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 KB | None | 0 0
  1. Art.all(:order => "created_at desc", :limit => 10, :group => "user_id")
  2.  
  3. Art Load (18.4ms) SELECT "arts".* FROM "arts" GROUP BY user_id ORDER BY created_at desc LIMIT 10
  4. ActiveRecord::StatementInvalid: PGError: ERROR: column "arts.id" must appear in the GROUP BY clause or be used in an aggregate function
  5. LINE 1: SELECT "arts".* FROM "arts" GROUP BY user_id ORDER BY crea...
  6.  
  7. a | b
  8. ---|---
  9. 1 | 1
  10. 1 | 2
  11. 2 | 3
  12.  
  13. arts = Art.all(:order => "created_at desc", :limit => 10)
  14. grouped_arts = arts.group_by {|art| art.user_id}
  15. # now you have a hash with following structure in grouped_arts
  16. # {
  17. # user_id1 => [art1, art4],
  18. # user_id2 => [art3],
  19. # user_id3 => [art5],
  20. # ....
  21. # }
  22.  
  23. SELECT arts.* FROM arts
  24. WHERE (arts.user_id, arts.created_at) IN
  25. (SELECT user_id, MAX(created_at) FROM arts
  26. GROUP BY user_id
  27. ORDER BY MAX(created_at) DESC
  28. LIMIT 10)
  29. ORDER BY created_at DESC
  30. LIMIT 10
  31.  
  32. Art.where("(arts.user_id, arts.created_at) IN
  33. (SELECT user_id, MAX(created_at) FROM arts
  34. GROUP BY user_id
  35. ORDER BY MAX(created_at) DESC
  36. LIMIT 10)").
  37. order("created_at DESC").
  38. page(params[:page]).
  39. per(params[:per])
Add Comment
Please, Sign In to add comment