【问题标题】:How can I find all cities with childs?我怎样才能找到所有有孩子的城市?
【发布时间】:2011-09-09 02:24:19
【问题描述】:

我有一个城市模型和一个商业模型。 业务 belogs_to :city

现在我想定义一个视图,其中仅列出那些有孩子的城市(在本例中为企业)。不应考虑空城(指仍没有新增业务的城市)。如果可能,列表的排序方式应使企业最多的城市排在首位。

我找到了这样的解决方案:

@cities = City.find :all, 
       :joins => "INNER JOIN businesses ON businesses.city_id = cities.id", 
       :select => "cities.*, count(businesses.id) businesses_count", 
       :group => "businesses.city_id HAVING businesses_count > 0",
       :order => "businesses_count desc"

这很好用(排序尚未完成),但据我了解,这不适用于 Rails 3.1 和 3.2(我现在使用 3.0)。见http://m.onkey.org/active-record-query-interface

谁能告诉我如何以适合 Rails 3.1 和 3.2 的方式定义我的@cities?

谢谢!

@KandadaBoggu:

太好了,我非常喜欢你的回答 2),谢谢!!

只是评论:

我与 rails 生成迁移 add_businesses_count_to_cities business_count:integer

然后我需要编辑迁移:

class AddBusinessesCountToCities < ActiveRecord::Migration
  def self.up
    add_column :cities, :businesses_count, :integer, :default => 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

这很重要,将默认值设置为 0,然后使用当前企业数量更新城市。

我还将 counter_cache 添加到子(业务)中,例如: 属于_to :city, :counter_cache => true

这样效果很好。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3


    【解决方案1】:

    1) 不排序:

    City.joins(:businesses).select("DISTINCT cities.*")
    

    2) 使用counter_cache

    将名为business_countinteger 列添加到cities 表中。

    class City < ActiveRecord::Base
      has_many :businesses, :counter_cache => :business_count
    end
    

    现在您可以选择如下城市:

    City.where("business_count > 0").order(:business_count)
    

    3) 使用group by

    City.joins("
       ( SELECT a.id, COUNT(*) as business_count
         FROM   cities a, businesses b
         WHERE  a.id = b.city_id
         GROUP BY a.id 
       ) c ON cities.id = c.id ").
     select("cities.*, c.business_count AS business_count").
     order(:business_count)
    

    【讨论】:

      猜你喜欢
      • 2017-09-26
      • 1970-01-01
      • 1970-01-01
      • 2021-10-31
      • 2012-11-20
      • 1970-01-01
      • 2018-05-27
      • 2021-12-17
      • 2013-01-08
      相关资源
      最近更新 更多