【问题标题】:Ruby on Rails 2 query on association countRuby on Rails 2 查询关联计数
【发布时间】:2011-06-25 08:39:28
【问题描述】:

这个问题与 [1] 非常相似,只是我在 RoR 使用的是 Rails 2.3.5(是的,旧的)和一个完整的新手。我有两个模型,Configfile 和 Signoff。

我想找到所有签核数小于 2 的 Configfile。当然,我可以通过手动过滤数组来做到这一点,但是这个数据库很大而且速度很慢。

class Configfile < ActiveRecord::Base
  belongs_to :computer
  has_many :signoffs,
           :dependent => :destroy
end

class Signoff < ActiveRecord::Base
  belongs_to :configfile
end

这似乎在 Rails 中应该很容易做到,但我想不通。 到目前为止,我的查询看起来像这样,我还没有得到任何可以通过签核次数限制它的方法。

configs = c.configfiles.find(:all,
                             :include => :signoffs,
                             :order => 'filename')

[1]Rails 3 query on condition of an association's count

【问题讨论】:

    标签: ruby-on-rails ruby activerecord


    【解决方案1】:
    Configfile.find(:all, :group=>"configfile_id", :joins=>:signoffs, :having=>"count(*) &lt 2")
    

    这应该给您与等效的 rails3 相同的内容:

    Configfile.joins(:signoffs").group("configfiles.id").having("count_all < 2").count(:all)
    

    【讨论】:

    • 非常感谢!我得到的最终解决方案是:configfiles.find(:all, :group=&gt;"configfile_id", :joins=&gt;:signoffs, :having=&gt;"COUNT(*) &lt; 2")(将 count_all 更改为 COUNT(*) 并将 .count 更改为 .find)
    猜你喜欢
    • 2012-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多