gpt4 book ai didi

ruby-on-rails - 0 大小关联的 Rails Scope

转载 作者:行者123 更新时间:2023-12-02 00:31:49 24 4
gpt4 key购买 nike

我无法为所有没有条形图的 Foos 找出作用域方法。即:

class Foo < ActiveRecord::Base

has_may :bars

end

class Bar < ActiveRecord::Base

belongs_to :foo

end

我想编写一个作用域方法,返回所有没有条形的 foo。像这样的东西:

class Foo < ActiveRecord::Base

has_may :bars

scope :has_no_bars, includes(:bars).where("COUNT(foo.bars) = 0")

end

但我不明白适当的语法。有什么帮助吗?如果更容易,很高兴使用 MetaWhere 解决方案。

最佳答案

您需要子选择或外部连接+组+唯一来解决您的问题。据我所知,这在 Rails 的 AR 中是不可能的。

近似值是使用 AR 的 counter-cache功能并使您的查询像

scope :has_no_bars, where("bars_count = 0")

这不是 100% 正确的关系,但可以节省大量工作,而且扩展性更好。

关于ruby-on-rails - 0 大小关联的 Rails Scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6431250/

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