title: Rails has_many :through and N+1
body: <p>I have two associated models: Chat and User through Memberships model</p>
  
  <pre><code>class Chat &lt; ActiveRecord::Base
   has_many :memberships
   has_many :members, through: :memberships
  end
  
  class Membership &lt; ActiveRecord::Base
   belongs_to :chat
   belongs_to :member, class_name: "User", foreign_key: 'user_id'
  end
  </code></pre>
  
  <p>In the controller I retrieve records like that:</p>
  
  <pre><code>@chats = Chat.joins(:memberships).includes([:owner, :memberships=&gt;:member])
  .where("chats.owner_id = ? OR memberships.user_id = ?", current_user.id, current_user.id)
  </code></pre>
  
  <p>And in view I display chats with JBuilder like that: </p>
  
  <pre><code>json.extract! @chat, :id
     json.members @chat.memberships.order('id ASC') do |membership|
       json.name membership.member.name
     end
  end
  </code></pre>
  
  <p>But Rails generate a lot of db queries and the view rendering takes a long time:</p>
  
  <pre><code>Completed 200 OK in 1597ms (Views: 1393.8ms | ActiveRecord: 150.8ms)
  </code></pre>
  
  <p>How can I optimize and speed up these queries?</p>