4

多くの子を持つ単純な親オブジェクトがあります。名前付きスコープを使用して、特定の数の子を持つ親だけを戻す方法を理解しようとしています。

これは可能ですか?

class Foo < ActiveRecord::Base
    has_many :bars
    named_scope :with_no_bars, ... # count of bars == 0
    named_scope :with_one_bar, ... # count of bars == 1
    named_scope :with_more_than_one_bar, ... # count of bars > 1
end

class Bar < ActiveRecord::Base
    belongs_to :foo
end

私は次のようなことをしたいと思っていますFoo.with_one_bar

このようなものの親クラスにメソッドを書くことはできますが、名前付きスコープの力が欲しいです

4

2 に答える 2

11
class Foo < ActiveRecord::Base
  has_many :bars

  # I don't like having the number be part of the name, but you asked for it.
  named_scope :with_one_bar, :joins => :bars, :group => "bars.foo_id", :having => "count(bars.foo_id) = 1"

  # More generically...
  named_scope :with_n_bars, lambda {|n| {:joins => :bars, :group => "bars.foo_id", :having => ["count(bars.foo_id) = ?", n]}}
  named_scope :with_gt_n_bars, lambda {|n| {:joins => :bars, :group => "bars.foo_id", :having => ["count(bars.foo_id) > ?", n]}}

end

次のように呼び出されます。

Foo.with_n_bars(2)
于 2010-05-24T20:43:39.753 に答える
6

これにはカウンターキャッシュを使用します。したがって、次の移行が必要です。

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]

于 2010-05-24T20:57:34.453 に答える