2011-06-15 59 views
1

我有一些问题需要正确设置和关联,我在这里查看了所有关于多态关联的问题,但没有一个与我的情况相符。has_many through polymorphic

这里是一个最小的工作测试:

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 

,但显然这使我不能用用户作为标准协会:/

编辑:文件夹的父不能是文件夹本身,在这个代码父代只能是一个Site(它可以是一些其他的东西在真实的代码中,但它的工作原理是一样的)。

+0

如果一个文件夹中有一个文件夹作为其父母,你要返回父文件夹的用户(这将再次查询它的父母)?我不认为这是可能的,因为这可能是一个递归查询。 – Dogbert 2011-06-15 11:29:23

+0

该文件夹的父级不能是文件夹本身,我更新了问题。 – Schmurfy 2011-06-15 12:43:39

回答

1

我不认为Rails支持has_many:通过传递多态关联。

在Rails 3.1 RC 1,我得到在轨控制台明确的例外:

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'. 
+0

我接受了这个答案,因为我怀疑还会有更多的事情发生,我最终在大部分时间想要使用的墙都会碰到很多通过:/ – Schmurfy 2011-08-05 19:36:17