加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 23:35:26 所属栏目:百科 来源:网络整理
导读:我有一个有很多孩子的简单父对象.我正在试图弄清楚如何使用命名范围来恢复具有特定数量的孩子的父母. 这可能吗? class Foo ActiveRecord::Base has_many :bars named_scope :with_no_bars,... # count of bars == 0 named_scope :with_one_bar,... # count
我有一个有很多孩子的简单父对象.我正在试图弄清楚如何使用命名范围来恢复具有特定数量的孩子的父母.

这可能吗?

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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读