I’m trying to define multiple polymorphic relations (has_many_polymorphs plugin
) from a single parent to same children.
Note has many viewers
Note has many editors
Viewers could be either Users or Groups
Editors could be either Users or Groups
Permission is the association model with note_id
, viewer_id
, viewer_type
, editor_id
, editor_type
fields
Everything works out as expect as long as I have only one has_many_polymorphs relation defined in Note model
class User < ActiveRecord::Base; end
class Group < ActiveRecord::Base; end
class Note < ActiveRecord::Base has_many_polymorphs :viewers, :through => :permissions, :from => [:users, :groups] end
class Permission < ActiveRecord::Base belongs_to :note belongs_to :viewer, :polymorphic => true end
Note.first.viewers << User.first # => [#<User id: 1, ….>]
Note.first.viewers << Group.first # => [#<User id: 1, ….>, #<Group …>]
Note.first.viewers.first # => #<User ….>
Note.first.viewers.second # => #<Group ….>
Now, problems start to appear when I add the second relation
class Note < ActiveRecord::Base has_many_polymorphs :viewers, :through => :permissions, :from => [:users, :groups] has_many_polymorphs :editors, :through => :permissions, :from => [:users, :groups] end
class Permission < ActiveRecord::Base belongs_to :note belongs_to :viewer, :polymorphic => true belongs_to :editor, :polymorphic => true end
Note.first.viewers << User.first # => [#<User id: ....>]
>>>>>>>>
Note.first.editors << User.first
NoMethodError: You have a nil object when you didn’t expect it!
The error occurred while evaluating nil.constantize
… vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/base.rb:18:in `instantiate’
—-
I’ve tried refining the definition of has_many_polymorphs
but it didn’t work. Not even with an STI model for ViewPermission \< Permission
, and EditPermission \< Permission
.
Any thoughts / workarounds / issue pointers are appreciated.
Rails 2.3.0
Posted to:
- Stack Overflow (http://stackoverflow.com/questions/983225/multiple-hasmanypolymorphs-in-one-model)
- Github (issue) (http://github.com/fauna/has_many_polymorphs/issues/#issue/3)