开发者

has_many through polymorphic

I have some problems to set up and association correctly, I looked at all the questions asked about polymorphic association here but none seems to match my case.

Here is a minimal working test:

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

And here is my schema:

# 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

Is there any way to make this works as an association ?

For now I ended up replacing the users association with:

def users
  parent.users
end

but obviously that prevents me from using users as a standard association :/

Edit: The folder's开发者_运维百科 parent cannot be a folder itself, in this code the parent can only be a Site (it can be some other things in the real code but it works the same way).


I don't think Rails supports has_many :through passing through polymorphic associations.

In Rails 3.1 rc 1, I get an explicit exception in the rails console:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜