rails --version
2.3.16
ruby --version
1.8.7
楷模:
class AToB
belongs_to :a
belongs_to :b
default_scope :include => [:a, :b]
end
class A
has_many :a_to_bs
has_many :bs, :through => :a_to_bs
named_scope :twos, :conditions => { :var => 2 }
named_scope :buzzed, :conditions => { :fizz => ['buzz'] }
end
class B
has_many :a_to_bs
has_many :as, :through => :a_to_bs
end
MYSQL查询:
SELECT COUNT(DISTINCT a.id), COUNT(DISTINCT c.id)
FROM a_to_b
INNER JOIN a on a.id = a_to_b.a_id
INNER JOIN b on b.id = a_to_b.b_id
WHERE (a.var = 2 AND a.fizz in ('buzz') AND
(b.foo = TRUE OR b.bar = TRUE OR (b.moo = TRUE AND a_to_b.goo = FALSE))
)
也需要这种变化
SELECT COUNT(DISTINCT a.id), COUNT(DISTINCT c.id)
FROM a_to_b
INNER JOIN a on a.id = a_to_b.a_id
INNER JOIN b on b.id = a_to_b.b_id
WHERE (a.var = 2 AND a.fizz in ('buzz') AND
NOT (b.foo = TRUE OR b.bar = TRUE OR (b.moo = TRUE AND a_to_b.goo = FALSE))
)
我已经用谷歌搜索了无数更简单的例子,阅读rails docs等都无济于事。