title: Ruby on Rails: flatten arry of hashes & group by key
body: <p>Let me begin by explaining what I want to do:</p>
  
  <p>I have these models:</p>
  
  <pre><code>"Question"
  name:string
  belongs_to :Category
  
  "Category"
  name:string
  has_many :Questions
  
  AgendaItem
  title:string
  body:string
  belongs_to :Category
  
  "Meeting"
  has_many :Questions
  has_many :AgendaItems
  </code></pre>
  
  <p>The process is thus:
  User creates a meeting &amp; adds many questions to it from many different categories (~12 categories, each with 10-20 questions).</p>
  
  <p>I've got that bit working, so I have a Meeting with many Questions on it.</p>
  
  <p>Now, when a User performs a specific action on a meeting called "Finalise" I want to  create an AgendaItem (using the Meeting's Questions) for each distinct Category , the :title of the AgendaItem should be the :name of the Category and the :body of it should be all the questions that have been selected under that category </p>
  
  <pre><code>eg: &lt;ul&gt;&lt;li&gt;Question1&lt;/li&gt;&lt;li&gt;Question2&lt;/li&gt;...&lt;/ul&gt;
  </code></pre>
  
  <p>I could do this in a nasty big loop (and check whether the current Category of the question I'm on is now different to the previous one &amp; create a new AgendaItem), or use two loops (one to create distinct AgendaItems, and then one to pop the questions into the :body)</p>
  
  <p>But I'm sure there's a better way of doing it, using arrays &amp; inject.</p>
  
  <p>My current code creates an array of hashes (I think) like this:</p>
  
  <pre><code>[{:id=&gt;1, :question=&gt;"Question1"}, {:id=&gt;1, :question=&gt;"Question3"},{:id=&gt;3, :question=&gt;Question10}]
  </code></pre>
  
  <p>This is the code that does that:</p>
  
  <pre><code>@meeting = Meeting.find &lt;the_id&gt;
  array = @meeting.questions.all.map { |q| { id: q.category.id, question: q.name } }
  </code></pre>
  
  <p>Where :id is the :id of the Category and :question is the :name of the Question</p>
  
  <p>I think I want to end up with this:</p>
  
  <pre><code>[{:id=&gt;1, :question=&gt;"&lt;li&gt;Question1&lt;/li&gt;&lt;li&gt;Question3&lt;/li&gt;"},{:id=&gt;3, :question=&gt;&lt;li&gt;Question10&lt;/li&gt;}]
  </code></pre>
  
  <p>Then I can loop over it &amp; create an AgendaItem from the :id (key) and set it's body to be the :question (value).</p>