Skip to content

Instantly share code, notes, and snippets.

@davetapley
Created January 27, 2013 19:40
Show Gist options
  • Save davetapley/4650010 to your computer and use it in GitHub Desktop.
Save davetapley/4650010 to your computer and use it in GitHub Desktop.
# you have your list of the user's posts,
# these are just in whatever order your DB gets them, which is probably (but not guaranteed) to be ordered by the post id:
@posts = user.posts
@posts.map { |p| [p.id, p.category_id] } # [[1,3], [2,5], [3,3], [4,1]]
# you can specify that you'd like the order explicitly like this,
# here we ask for them ASCending, you have to pick one, but it probably doesn't matter in your case:
@posts = user.posts.order('category_id ASC')
@posts.map { |p| [p.id, p.category_id] } # [[4,1], [3,3], [1,3], [2,5]]
# what I think you want is to actually group_by, note that this is a Ruby method: http://api.rubyonrails.org/classes/Enumerable.html#method-i-group_by
@posts = user.posts.order('category_id ASC').group_by(&:category)
@posts.map { |cat, ps| [cat.id, ps.map(&:id)] } # [[1, [4]], [3, [3,1]], [5, [2]]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment