Created
January 27, 2013 19:40
-
-
Save davetapley/4650010 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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