Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I find all cities with childs?
    primarykey
    data
    text
    <p>I have a City model and a Business model. Business belogs_to :city</p> <p>Now I want to define a view with a list of only those cities who have a child (in this case a business). Empty cities (means cities which still have no business added) should not be considered. If possible the list should be sorted in a way that the city with most businesses is on the top.</p> <p>I found a solution like this:</p> <pre><code>@cities = City.find :all, :joins =&gt; "INNER JOIN businesses ON businesses.city_id = cities.id", :select =&gt; "cities.*, count(businesses.id) businesses_count", :group =&gt; "businesses.city_id HAVING businesses_count &gt; 0", :order =&gt; "businesses_count desc" </code></pre> <p>This works fine (sorting is not yet done), but as far as I understood this will not work with Rails 3.1 and 3.2 (I use 3.0 now). See <a href="http://m.onkey.org/active-record-query-interface" rel="nofollow">http://m.onkey.org/active-record-query-interface</a></p> <p>Can anybody let me know how to define my @cities in a way that is ok for Rails 3.1 and 3.2?</p> <p>Thank you!</p> <p>@KandadaBoggu:</p> <p>Great, I very much like your answer 2), thanks!!</p> <p>Just a comment:</p> <p>I migrated with rails generate migration add_businesses_count_to_cities businesses_count:integer</p> <p>Then I needed to edit the migration:</p> <pre><code>class AddBusinessesCountToCities &lt; ActiveRecord::Migration def self.up add_column :cities, :businesses_count, :integer, :default =&gt; 0 City.reset_column_information City.all.each do |c| c.update_attribute :businesses_count, c.businesses.count end end def self.down remove_column :cities, :businesses_count end end </code></pre> <p>This is important to set a default value of 0 and then update the cities with the current number of businesses.</p> <p>I also added the counter_cache to the child (business) like: belongs_to :city, :counter_cache => true</p> <p>This way it works great.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload