Ruby   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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-on-rails – 使用带有子模型计数的named_scope全部内容,希望文章能够帮你解决ruby-on-rails – 使用带有子模型计数的named_scope所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。