2011-12-05 8 views

答えて

1
# migration 
class AddCounterCacheToCountries < ActiveRecord::Migration 
    add_column :countries, :hotel_count, :integer, :default => 0 
end 

# models 
class Country 
    has_many :hotels 
    scope :with_hotels, where('hotel_count > 0') 
end 

class Hotel 
    belongs_to :country, :counter_cache => true 
end 

# controller 
def index 
    @countries = Country.with_hotels.all 
end 

に感謝し、それはそれにそこにあるおよそすべてです。

+0

カウンタキャッシュは最適なソリューションですか? – Sebastien

+0

また、ジョインを使用すると、関連するホテルがない国は返されませんが、それはパフォーマンスが悪く、DBクエリを追加しないとホテルの数だけ国オブジェクトを照会できるという利便性がありません。 – coreyward

+0

ありがとうございます – Sebastien

関連する問題