单表继承(STI)和has_and_belongs_to_many(HABTM)关联的错误

时间:2011-05-29 15:21:21

标签: ruby-on-rails ruby-on-rails-3 activerecord single-table-inheritance

使用Rails 3.0.7,并拥有以下4个模型:

class User < ActiveRecord::Base
end

class Administrator < User
  has_and_belongs_to_many :clients
end

class Client < ActiveRecord::Base
  has_and_belongs_to_many :administrators
  has_and_belongs_to_many :meetings
end

class Meeting < ActiveRecord::Base
  has_and_belongs_to_many :clients

  def self.foo
    self.joins(:clients => :administrators)
  end
end

通话:

Meeting.foo.to_sql

产生

SELECT meetings.*
FROM meetings
INNER JOIN clients_meetings ON clients_meetings.event_id = meetings.id
INNER JOIN clients ON clients.id = clients_meetings.child_id
INNER JOIN clients_administrators ON clients_administrators.child_id = clients.id
INNER JOIN users ON users.type = 'Administrator'

但似乎错过了“clients_administrators”和“users”之间的最终连接关系。我认为最后一行SQL应该是:

INNER JOIN users ON users.id = clients_administrators.user_id
WHERE users.type = 'Administrator'

这是一个错误吗?或者我误解了什么?

由于

1 个答案:

答案 0 :(得分:1)

这似乎是bug,但已在Rails 3.1中解决。