has_many_polymorphs icon indicating copy to clipboard operation
has_many_polymorphs copied to clipboard

Multiple has_many_polymorphs in one model

Open tamersalama opened this issue 15 years ago • 2 comments

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

tamersalama avatar Jun 11 '09 19:06 tamersalama

Posted on StackOverflow as well - http://stackoverflow.com/questions/983225/multiple-hasmanypolymorphs-in-one-model

tamersalama avatar Jun 11 '09 19:06 tamersalama

best bet is to make a failing test and fix it yourself; this project is in patch-accepting-mode only :-/

ghost avatar Aug 05 '09 21:08 ghost