代码之家  ›  专栏  ›  技术社区  ›  joshsz

如何在所有模型上添加具有多个关联

  •  1
  • joshsz  · 技术社区  · 16 年前

    现在我有一个初始值设定项可以执行此操作:

    ActiveRecord::Base.send :has_many, :notes, :as => :notable ActiveRecord::Base.send :accepts_nested_attributes_for, :notes

    它可以很好地构建关联,除非当我加载使用它的视图时,第二次加载会给我: can't dup NilClass 来自:

    /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2184:in `dup'
    /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2184:in `scoped_methods'
    /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2188:in `current_scoped_methods'
    /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2171:in `scoped?'
    /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2439:in `send'
    /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2439:in `initialize'
    /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/reflection.rb:162:in `new'
    /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/reflection.rb:162:in `build_association'
    /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/associations/association_collection.rb:423:in `build_record'
    /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/associations/association_collection.rb:102:in `build'
    (my app)/controllers/manifests_controller.rb:21:in `show'
    

    有什么想法吗?我这样做是不是不对?有趣的是,如果我将关联转移到目前正在使用的模型上,我不会得到这个错误。我想我一定是在错误地建立全球联盟。

    4 回复  |  直到 16 年前
        1
  •  7
  •   John Topley    16 年前

    您声明您有许多模型,所有这些模型都需要这个关联。如果是我,我会使用创建包含关联的基础模型类的方法,然后让所有其他模型从中继承。类似:

    class NotableModel < ActiveRecord::Base
    
      # Prevents ActiveRecord from looking for a database table for this class
      self.abstract_class = true
    
      has_many :notes, :as => :notable
      accepts_nested_attributes_for :notes  
    end
    
    class Foo < NotableModel
      ...
    end
    
    class Bar < NotableModel
      ...
    end
    

    在我看来,与使用隐藏在初始值设定项中的一点元编程相比,这种方法更加自我记录。

        2
  •  0
  •   Salil    16 年前

    看一看 unloadable 它可以帮助你

        3
  •  0
  •   amrnt    16 年前

    建议在每个模型中建立每个关联!这是制造这种东西的一种无用的干燥方法!总之,这是我的意见!

        4
  •  -1
  •   joshsz    16 年前

    多亏了丰富的Kilmer(信息醚),我们找到了优雅的(稍微不透明的)解决方法:

    # config/initializers/has_many_notes.rb
    module ActiveRecord
      class Base
        def self.inherited(klass)
          super
          klass.send :has_many, :notes, :as => :notable
          klass.send :accepts_nested_attributes_for, :notes
        end
      end
    end
    

    现在没有继承改变,而且非常干燥

    推荐文章