2011-06-15 45 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

相關問題