我会为此使用counter cache。因此,您需要进行以下迁移:
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") }
这样,您每次提出此类请求时都可以节省为每个 foo 计算 bars 的时间。
我在观看有关计数器缓存的 railscast 时产生了这个想法:http://railscasts.com/episodes/23-counter-cache-column
* What's new in Active Record [Rails 4 Countdown to 2013]