ruby-on-rails – 使用带有子模型计数的named_scope

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 使用带有子模型计数的named_scope前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个有很多孩子的简单父对象.我正在试图弄清楚如何使用命名范围来恢复具有特定数量的孩子的父母.

这可能吗?

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这样的事情

我可以在父类上编写类似这样的方法,但我宁愿拥有命名范围的强大功能

解决方法

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,:having => ["count(bars.foo_id) = ?",n]}}
  named_scope :with_gt_n_bars,:having => ["count(bars.foo_id) > ?",n]}}

end

像这样打电话:

Foo.with_n_bars(2)

猜你在找的Ruby相关文章