我有两个模型
class Foo < ActiveRecord::Base
# columns are
# max_spots
has_many :bars
end
class Bar < ActiveRecord::Base
# columns are
# a_id
belongs_to :foo
end
我需要获取所有 max_spots 大于与其关联的柱数的 Foos,但我需要通过事件记录来完成,而不是像这样遍历每个 Foos
class Foo
#bad
def self.bad_with_spots_left
all.select do |foo|
foo.max_spots - foo.bars.count > 0
end
end
#good but not working
def self.good_with_spots_left
joins(:bars).select('COUNT(bars.id) AS bars_count').where('max_spots - bars_count > 0')
end
end
我知道我可以只向 foo 添加一个计数器缓存,但我只是想知道如果没有它我该如何做到这一点。谢谢!
最佳答案
SQL 不允许在 WHERE 子句中使用别名,只能使用列名。
作为替代方案,您可以尝试其中之一:
在纯 SQL 中
def self.good_with_spots_left
where('foos.max_spots > (SELECT Count(*) FROM bars WHERE bars.a_id = foos.id)')
end
或者,使用 bit 或 ruby(第二个 select
在 ruby 中解释,因为它包含一个 &block)
def self.good_with_spots_left
joins(:bars).select('foos.*', COUNT(bars.id) AS bars_count').group('bars.a_id').select{|foo| foo.max_spots > foo.bars_count}
end
关于ruby-on-rails - 使用 Postgres,计算关联计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14641756/