我有一些问题需要正确设置和关联,我在这里查看了所有关于多态关联的问题,但没有一个与我的情况相符。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(它可以是一些其他的东西在真实的代码中,但它的工作原理是一样的)。
如果一个文件夹中有一个文件夹作为其父母,你要返回父文件夹的用户(这将再次查询它的父母)?我不认为这是可能的,因为这可能是一个递归查询。 – Dogbert 2011-06-15 11:29:23
该文件夹的父级不能是文件夹本身,我更新了问题。 – Schmurfy 2011-06-15 12:43:39