title: Optimize a query using active record rails
body: <p>The DB relation in rails models:</p>
  
  <pre><code>Class User &lt; ActiveRecord::Base
    has_many :user_messages
    has_many :messages
  end
  
  Class UserMessage &lt; ActiveRecord::Base
    belongs_to :user
    belongs_to :message
  end
  
  Class Message &lt; ActiveRecord::Base
    belongs_to :user
    has_many :user_messages
  end
  </code></pre>
  
  <p>I want to optimize the following code:</p>
  
  <pre><code>ids.each do |id|
    user = User.find_by_id(id)
    unread_count = user.user_messages.where(:folder =&gt; user.inbox_id, :read =&gt; false).count
    puts "UserID #{id} ---- Unread Message count #{unread_count}"
  end
  </code></pre>
  
  <p>Can some tell me how can I optimize the above code using Active record or SQL Query. I basically want to reduce DB queries and time the above code take to complete the loop.</p>
  
  <p>Thanks in advance.</p>