title: Order by association's count
body: <p>I have a Country which has many Communities which have many Attractions</p>
  
  <pre class="lang-rb prettyprint-override"><code># Country
  has_many :communities
  
  # Community
  has_many :attractions
  
  # Attraction
  belongs_to :community
  </code></pre>
  
  <p>In my <code>Countries</code> controller I have this right now:</p>
  
  <pre><code>def show
    @communities = @country.communities.all.order('name asc').paginate(page: params[:page], per_page: 30)
  end
  </code></pre>
  
  <p>Which gives me the <code>Communities</code> ordered by name.</p>
  
  <hr>
  
  <p>How can I order by <code>Community.attractions.count</code>, order the community with the most attractions desc.</p>
  
  <hr>
  
  <h1>EDIT</h1>
  
  <p>I  changed @muhamad's answer slightly to get to work</p>
  
  <pre><code>@communities = Community.joins(:country, :attractions).select("countries.*, communities.*, count(attractions.community_id) as attractions_count").group("communities.id, countries.id").order("attractions_count desc").where("countries.id = ?", @country.id).paginate(page: params[:page], per_page: 30)
  </code></pre>
  
  <p>The problem is, every community with 0 attractions is not shown, how can I fix this?</p>