如何在所有模型上添加has_many关联

时间:2010-04-22 13:45:13

标签: ruby-on-rails ruby activerecord polymorphic-associations

现在我有一个执行此操作的初始化程序:

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 个答案:

答案 0 :(得分:7)

您声明您有许多模型,所有模型都需要此关联。如果是我,我会采用创建包含关联的基础模型类的方法,然后让所有其他模型继承它。类似的东西:

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

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

答案 1 :(得分:0)

看看unloadable它可能会对你有帮助

答案 2 :(得分:0)

建议在每个模型中进行每个关联!制作这样的东西是一种无用的DRY方式!根本,这是我的看法!

答案 3 :(得分:-1)

感谢Rich Kilmer(InfoEther),我们找到了优雅(并且略微不透明)的方法来解决这个问题:

# 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

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