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)

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...