0
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等都无济于事。

4

2 回答 2

0

让我试着回答这个问题。例如,您的模型在 Rails 中如下所示:

#a.rb
class A < ActiveRecord::Base 
  attr_accessible :var, :fizz
  has_many :a_to_bs
end

#b.rb
class B < ActiveRecord::Base
  attr_accessible :foo, :bar, :moo
  has_many :a_to_bs
end

#a_to_b.rb
class AToB < ActiveRecord::Base
  attr_accessible :goo, :a_id, :b_id, :a, :b
  belongs_to :a
  belongs_to :b
end

第一个的典型查询是:

records = AToB.where("a.var = ? AND a.fizz in (?) AND (b.foo = ? OR b.bar = ? OR 
          (b.moo = ? AND a_to_b.goo = ?))", 2, 'buzz', true, true, true, false)

对于第二个,它将是:

records = AToB.where("a.var = ? AND a.fizz in (?) AND NOT (b.foo = ? OR b.bar = ? OR
         (b.moo = ? AND a_to_b.goo = ?))", 2, 'buzz', true, true, true, false)

假设您提到的查询是正确的,答案是正确的。

于 2013-02-26T07:29:36.600 回答
0

这有点工作:

scope = A.twos.buzzed
scope.count(:joins => { :b => :a_to_b }, :conditions => "b.foo = TRUE OR b.bar = TRUE OR (b.moo = TRUE AND a_to_b.goo = FALSE)")

在我确定之前要再测试一下。

于 2013-02-26T11:40:11.557 回答