我有一些问题需要正确设置和关联,我查看了所有关于多态关联的问题,但似乎没有一个与我的情况相匹配。
下面是一个最小的工作测试:
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但很明显,这会阻止我将用户用作标准关联:
编辑:文件夹的父文件夹不能是文件夹本身,在这段代码中,父文件夹只能是一个站点(它可以是真实代码中的一些其他东西,但它的工作方式是相同的)。
发布于 2011-08-03 09:37:00
我不认为Rails支持has_many :通过多态关联传递。
在Rails 3.1RC 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'.https://stackoverflow.com/questions/6356735
复制相似问题