Skip to content

Instantly share code, notes, and snippets.

@rishighan
Last active August 29, 2015 14:05
Show Gist options
  • Save rishighan/c7d05d13d62131d51fad to your computer and use it in GitHub Desktop.
Save rishighan/c7d05d13d62131d51fad to your computer and use it in GitHub Desktop.
How to create a hash from a collection in the view ?
h =[]
@posts.each do |p|
p.categories.each do |cat|
h << {p.id => cat.title}
end
end
@rishighan
Copy link
Author

 [{30=>"Projects"}, {30=>"Hero"}, {41=>"General"}, {41=>"Hero"}, {37=>"Projects"}, {38=>"Projects"}, {38=>"Hero"}, {29=>"General"}, {29=>"Hero"}, {39=>"General"}, {39=>"Hero"}, {40=>"Technical"}, {40=>"Hero"}, {31=>"General"}, {31=>"Hero"}, {42=>"General"}, {42=>"Highlight"}] 

@rishighan
Copy link
Author

To achieve the deisred result

[30=>{"General", "Technical"}, 40 => {"Technical"}]

use

@log.map { |p| [p.id, p.categories.map(&:title)] }.to_h

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment