title: Convert query in select and group in rails
body: <p>I am learning <code>join</code> tables query generation. I can achieve my goal without <code>join</code> table using association. But now my question is how can I get the same result as using <code>join</code>, <code>select</code> and <code>group</code>?</p>
  
  <p><strong>Models:</strong></p>
  
  <pre><code>class User &lt; ActiveRecord::Base
    has_many :messsages         
  end
  
  class Messsage &lt; ActiveRecord::Base
    belongs_to :user
  end
  </code></pre>
  
  <p><strong>Table Structure:</strong></p>
  
  <pre><code>#users : id , first_name , last_name
  #messages: id, subject , description , sender_id, recipient_id
  </code></pre>
  
  <p><strong>Controller:</strong></p>
  
  <pre><code> @messsages = Messsage.where(recipient_id: current_user.id)
   @sender_list = @messsages.group(:sender_id).count
   =&gt; Expected correct output: {1=&gt;1, 2=&gt;1, 3=&gt;2, 4=&gt;3} #getting as result 
  </code></pre>
  
  <p>by this I am getting from which sender_id I get how much messages. I am using <code>PostgreSQL</code> </p>
  
  <p><strong>My try:</strong></p>
  
  <pre><code>@sender_list = Messsage.joins(:user).select("users.id, users.first_name").group("users.id , messsages.sender_id")
  </code></pre>
  
  <p><strong>Error:</strong></p>
  
  <pre><code>PG::UndefinedColumn: ERROR:  column messsages.user_id does not exist
  LINE 1: ... "messsages" INNER JOIN "users" ON "users"."id" = "messsages...
                                                               ^
  : SELECT users.id, users.first_name FROM "messsages" INNER JOIN "users" ON "users"."id" = "messsages"."user_id" GROUP BY users.id , messsages.sender_id
  </code></pre>
  
  <h2>Update:</h2>
  
  <p>I have update my form code also so you may have better idea:</p>
  
  <pre><code>&lt;%= form_for(@messsage) do |f| %&gt;
    &lt;div class="field"&gt;
      &lt;%= f.label :sender_id %&gt;&lt;br&gt;
      &lt;%= f.collection_select :sender_id, User.all, :id, :id  %&gt;
    &lt;/div&gt;
    &lt;div class="field"&gt;
      &lt;%= f.label :subject %&gt;&lt;br&gt;
      &lt;%= f.text_field :subject %&gt;
    &lt;/div&gt;
    &lt;div class="field"&gt;
      &lt;%= f.label :description %&gt;&lt;br&gt;
      &lt;%= f.text_area :description %&gt;
    &lt;/div&gt;
    &lt;div class="field"&gt;
      &lt;%=  f.hidden_field :recipient_id , :value =&gt; current_user.id %&gt;
    &lt;/div&gt;
    &lt;div class="actions"&gt;
      &lt;%= f.submit %&gt;
    &lt;/div&gt;
  &lt;% end %&gt;
  </code></pre>
  
  <p>Screenshot of Page:
  <img src="https://i.stack.imgur.com/nhBEd.png" alt="enter image description here"></p>