我到处搜索指向此的指针,但找不到指针。基本上,我想做其他人想要做的事情,当他们在a:has_many中创建多态关系时:通过方式......但我想在模块中做到这一点。我一直陷入困境,认为我必须忽略一些简单的事情。
即便:
module ActsPermissive
module PermissiveUser
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def acts_permissive
has_many :ownables
has_many :owned_circles, :through => :ownables
end
end
end
class PermissiveCircle < ActiveRecord::Base
belongs_to :ownable, :polymorphic => true
end
end
使用如下所示的迁移:
create_table :permissive_circles do |t|
t.string :ownable_type
t.integer :ownable_id
t.timestamps
end
当然,这个想法是,act_permissive的任何载荷都可以拥有它拥有的圆圈列表。
对于简单的测试,我有
it "should have a list of circles" do
user = Factory :user
user.owned_circles.should be_an_instance_of Array
end
失败了:
Failure/Error: @user.circles.should be_an_instance_of Array
NameError: uninitialized constant User::Ownable
我尝试过:在has_many:ownables行上使用:class_name => 'ActsPermissive::PermissiveCircle'
,该行失败并显示:
Failure/Error: @user.circles.should be_an_instance_of Array
ActiveRecord::HasManyThroughSourceAssociationNotFoundError:
Could not find the source association(s) :owned_circle or
:owned_circles in model ActsPermissive::PermissiveCircle.
Try 'has_many :owned_circles, :through => :ownables,
:source => <name>'. Is it one of :ownable?
在遵循建议并设置:source => :ownable
时失败
Failure/Error: @user.circles.should be_an_instance_of Array
ActiveRecord::HasManyThroughAssociationPolymorphicSourceError:
Cannot have a has_many :through association 'User#owned_circles'
on the polymorphic object 'Ownable#ownable'
这似乎表明,使用非多态通过做事是必要的。所以我添加了一个类似于the setup here的circle_owner类:
module ActsPermissive
class CircleOwner < ActiveRecord::Base
belongs_to :permissive_circle
belongs_to :ownable, :polymorphic => true
end
module PermissiveUser
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def acts_permissive
has_many :circle_owners, :as => :ownable
has_many :circles, :through => :circle_owners,
:source => :ownable,
:class_name => 'ActsPermissive::PermissiveCircle'
end
end
class PermissiveCircle < ActiveRecord::Base
has_many :circle_owners
end
end
迁移:
create_table :permissive_circles do |t|
t.string :name
t.string :guid
t.timestamps
end
create_table :circle_owner do |t|
t.string :ownable_type
t.string :ownable_id
t.integer :permissive_circle_id
end
仍然失败:
Failure/Error: @user.circles.should be_an_instance_of Array
NameError:
uninitialized constant User::CircleOwner
这让我们回到了开始。
答案 0 :(得分:1)
事实证明,将class_name添加到:has_many定义实际上都有效(有人对此发表了评论,但他们删除了他们的评论)。它在我的非简化程序中不起作用,因为我的程序中的其他东西导致了一个级联错误,看起来是:has_many定义的本地错误。
简短的故事:对于实际上并不是问题的事情来说,这是一个很大的麻烦。布莱什