0

我正在尝试定义has_many_polymorphs plugin从单个父级到相同子级的多个多态关系 ()。

笔记有很多查看者
笔记有很多编辑者
查看者可以是用户或组
编辑者可以是用户或组权限是具有, , , ,字段
的关联模型note_idviewer_idviewer_typeeditor_ideditor_type

只要我在 Note 模型中只定义了一个 has_many_polymorphs 关系,一切都会按预期进行

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 ....>

现在,当我添加第二个关系时,问题开始出现

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'

我已经尝试改进定义,has_many_polymorphs但没有奏效。甚至没有用于ViewPermission < Permission和的 STI 模型EditPermission < Permission

感谢任何想法/解决方法/问题指针。

导轨 2.3.0

4

2 回答 2

0

你不需要添加

has_many :permissions

到你的笔记。供参考。我用过has_many_polymorphs一次,但后来放弃了,它没有按预期工作。

您可以发布您用于权限的架构吗?我的猜测是问题的根源在那里,你需要在模式中有多个类型、id 对,因为你有两个不同belongs_to的定义。

编辑:

我看到你也在 github 上发布了这个问题。不确定您是否尝试过使用双面多态性。你可能有......就像我说的,我对这个插件没有印象,因为它在我使用它时带来了一些不稳定。

== Double-sided polymorphism

Double-sided relationships are defined on the join model:

      class Devouring < ActiveRecord::Base
        belongs_to :guest, :polymorphic => true
        belongs_to :eaten, :polymorphic => true

        acts_as_double_polymorphic_join(
          :guests =>[:dogs, :cats], 
          :eatens => [:cats, :birds]
        )       
      end


Now, dogs and cats can eat birds and cats. Birds can't eat anything (they aren't <tt>guests</tt>) and dogs can't be 
eaten by anything (since they aren't <tt>eatens</tt>). The keys stand for what the models are, not what they do. 
于 2009-06-11T19:59:34.680 回答
0

@驯兽师

我遇到了同样的错误。问题是has_many_polymorphs使用大规模关联在连接表中创建记录并且失败了。我在课堂上添加了 attr_accessible :note_id:editor_id:editor_typePermission然后它就起作用了。(注意:我用你的型号代替了我的。)

我没有过多地研究它,但我很好奇是否有办法改变这种行为。我对这个框架相当陌生,让任何敏感的东西(如订单-支付关联)被大量分配似乎是在要求自己开枪。让我知道这是否解决了您的问题,以及您是否解决了其他问题。

最好的,
史蒂夫

于 2009-06-27T14:26:20.800 回答