繁体   English   中英

has_many通过多态

[英]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(在实际代码中可以是其他一些东西,但其工作方式相同)。

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

在Rails 3.1 rc 1中,我在rails控制台中得到了一个明确的异常:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM