我到处搜索指向此的指针,但找不到。基本上,当其他人在 :has_many、:through 方式中创建多态关系时,我想做其他人想做的事情……但我想在模块中做。我一直被卡住,并认为我必须忽略一些简单的事情。
以机智:
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
当然,这个想法是任何加载acts_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
我尝试过::class_name => 'ActsPermissive::PermissiveCircle'
在 has_many :ownables 行上使用,失败并显示:
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'
这似乎表明用非多态性做事是必要的。所以我添加了一个与此处设置类似的 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
这让我们回到了起点。
- 我怎样才能在一个模块上做一个看起来相当常见的多态 :has_many, :through ?
- 或者,是否有一种好方法可以让任意对象以与模块一起使用的类似方式收集对象?