1

现在我有一个初始化器可以做到这一点:

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

4 回答 4

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

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

于 2010-04-22T14:41:38.323 回答
0

看看unloadable它可能对你有帮助

于 2010-04-22T14:04:05.553 回答
0

建议在每个模型中进行每个关联!这是一种无用的 DRY 方法来制作这样的东西!总之,这是我的意见!

于 2010-04-22T14:06:35.420 回答
-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

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

于 2010-04-22T14:56:54.743 回答