gpt4 book ai didi

ruby-on-rails - 将 named_scope 与子模型的计数一起使用

转载 作者:行者123 更新时间:2023-12-04 21:54:48 24 4
gpt4 key购买 nike

我有一个简单的父对象,有很多 child 。我试图弄清楚如何使用命名范围来带回具有特定数量 child 的 parent 。

这可能吗?

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, :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)

关于ruby-on-rails - 将 named_scope 与子模型的计数一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2900031/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com