これにはカウンターキャッシュを使用します。したがって、次の移行が必要です。
class AddBarCount < ActiveRecord::Migration
def self.up
add_column :foos, :bars_count, :integer, :default => 0
Foo.reset_column_information
Foo.all.each do |p|
p.update_attribute :bars_count, p.bars.length
end
end
def self.down
remove_column :foos, :bars_count
end
end
Bar
次のようにモデルを変更する必要があります。
class Bar < ActiveRecord::Base
belongs_to :foo, :counter_cache => true
end
のカウントがモデルにbars
キャッシュされるようになりました。foo
これにより、カウントのクエリが高速化されますbars
。
あなたの named_scopes も次のようになります。
#rails 2
named_scope :with_no_bars, :conditions => { :bars_count => 0 }
named_scope :with_one_bar, :conditions => { :bars_count => 1 }
named_scope :with_more_than_one_bar, :conditions => ["bars_count > 1"]
#rails 3 & ruby 1.9+
scope :with_no_bars, where(bars_count: 0)
scope :with_one_bar, where(bars_count: 1)
scope :with_more_than_on_bar, where("bars_count > 1")
#rails 4* & ruby 1.9+
scope :with_no_bars, -> { where(bars_count: 0) }
scope :with_one_bar, -> { where(bars_count: 1) }
scope :with_more_than_one_bar, -> { where("bars_count > 1") }
そうすれば、そのようなリクエストを行うたびにbars
カウントする時間を節約できます。foo
カウンターキャッシュに関するRailscastを見て、このアイデアを得ました:http://railscasts.com/episodes/23-counter-cache-column
* Active Record の新機能 [Rails 4 カウントダウン 2013]