has_many通过多态

问题描述

| 我有一些问题需要正确设置和关联,我在这里查看了所有关于多态关联的问题,但似乎没有一个与我的情况相符。 这是一个最小的工作测试:
require \'rubygems\'

gem \'activerecord\',\'3.0.8\'

require \'active_record\'
require \'MysqL\'

ActiveRecord::Base.establish_connection(
  :adapter => \'MysqL\',:database => \'test_db\',:user => \'root\'
)

class User < ActiveRecord::Base
  belongs_to :site

end

class Site < ActiveRecord::Base
  has_many :folders,:as => :parent
  has_many :users

end

class Folder < ActiveRecord::Base
  belongs_to :parent,:polymorphic => true
  has_many :users,:through => :parent
end


p Folder.first.users
# => NameError: uninitialized constant Folder::Parent
这是我的架构:
# inimal database schema :
# 
# create_table :sites do |t|
#   t.string      :name,:null => false
# end
# 
# create_table :users do |t|
#   t.string      :login,:null => false
#   t.integer     :site_id,:null => false
# end
# 
# create_table :folders do |t|
#   t.string      :label,:null => false
#   t.string      :parent_type,:null => false
#   t.integer     :parent_id,:null => false
# end
有什么办法可以使它作为关联起作用? 现在,我最终将用户关联替换为:
def users
  parent.users
end
但显然,这阻止了我将用户用作标准关联:/ 编辑:文件夹的父文件夹不能是文件夹本身,在此代码中,父文件夹只能是站点(在实际代码中可以是其他一些东西,但其工作方式相同)。     

解决方法

        我不认为Rails支持has_many:通过传递多态关联。 在Rails 3.1 rc 1中,我在rails控制台中得到了一个明确的异常:
ruby-1.9.2-p180 :011 > p Folder.first.users
  Folder Load (0.1ms)  SELECT \"folders\".* FROM \"folders\" LIMIT 1
ActiveRecord::HasManyThroughAssociationPolymorphicThroughError: Cannot have a 
has_many :through association \'Folder#users\' which goes through the 
polymorphic association \'Folder#parent\'.