我有一些問題需要正確設置和關聯,我在這裏查看了所有關於多態關聯的問題,但沒有一個與我的情況相符。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