1

現在、これを行う初期化子があります。

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

それは、それを使用するビューをロードするときを除いて、関連付けをうまく構築します.2番目のロードは私に与えます: can't dup NilClass from:

/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

(InfoEther の) Rich 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

継承の変更はなく、非常に DRY です

于 2010-04-22T14:56:54.743 に答える