2011-07-27 18 views
3

レコードに単純な階層をエンコードしようとしていますが、私は奇妙なエラーに遭遇しています。ActiveRecord - 未定義のメソッド 'match'

require 'rubygems' 
require 'active_record' 

ActiveRecord::Base.establish_connection(
    :adapter => "sqlite3", 
    :database => ":memory:" 
) 
ActiveRecord::Schema.define do 
    create_table :foos do |t| 
    t.string :name, :null => false 
    t.integer :parent_id, :default => nil 
    end 
end 

class Foo < ActiveRecord::Base 
    belongs_to :parent, :class_name => Foo 
end 

bar = Foo.create(:name => 'Bar') 
p [ :bar, bar ] 

baz = Foo.create(:name => 'Baz', :parent_id => bar.id) 
p [ :baz, baz ] 

quux = Foo.create(:name => 'Quux', :parent => bar) 
p [ :quux, quux ] 

私はそれを実行すると、私が手:

% ruby temp.rb 
-- create_table(:foos) 
    -> 0.0269s 
[:bar, #<Foo id: 1, name: "Bar", parent_id: nil>] 
[:baz, #<Foo id: 2, name: "Baz", parent_id: 1>] 
/path/to/activerecord-3.0.9/lib/active_record/base.rb:1014:in `method_missing': undefined method `match' for Foo(id: integer, name: string, parent_id: integer):Class (NoMethodError) 
     from /path/to/activerecord-3.0.9/lib/active_record/base.rb:1184:in `compute_type' 
     from /path/to/activerecord-3.0.9/lib/active_record/reflection.rb:162:in `send' 
     from /path/to/activerecord-3.0.9/lib/active_record/reflection.rb:162:in `klass' 
     from /path/to/activerecord-3.0.9/lib/active_record/associations/association_proxy.rb:262:in `raise_on_type_mismatch' 
     from /path/to/activerecord-3.0.9/lib/active_record/associations/belongs_to_association.rb:23:in `replace' 
     from /path/to/activerecord-3.0.9/lib/active_record/associations.rb:1465:in `parent=' 
     from /path/to/activerecord-3.0.9/lib/active_record/base.rb:1564:in `send' 
     from /path/to/activerecord-3.0.9/lib/active_record/base.rb:1564:in `attributes=' 
     from /path/to/activerecord-3.0.9/lib/active_record/base.rb:1560:in `each' 
     from /path/to/activerecord-3.0.9/lib/active_record/base.rb:1560:in `attributes=' 
     from /path/to/activerecord-3.0.9/lib/active_record/base.rb:1412:in `initialize' 
     from /path/to/activerecord-3.0.9/lib/active_record/base.rb:502:in `new' 
     from /path/to/activerecord-3.0.9/lib/active_record/base.rb:502:in `create' 
     from temp.rb:25 

私はFooの定義にhas_many :children, :class_name => Foo, :as => :parentを追加し、代わりにquux = bar.children.create(name => 'Quux')を行い、私は同様のエラーを取得する場合。

私は間違っていますか?

答えて

11

belongs_toへの:class_nameのオプションは、クラスではなく文字列を必要とします。

class Foo < ActiveRecord::Base 
    belongs_to :parent, :class_name => "Foo" 
end 

ます。またacts_as_treeまたはいくつかの他のプラグインを使用して検討する必要があります(多くありますが、私は現在好まれているものを覚えていません)階層のこの種を扱うために設計されました。それはあなたの人生を道路の下で楽にするかもしれません。

+0

ありがとうございます!私は愚か者だと思う:) 'acts_as_tree'は(私の実際のケースでは)それはちょうど2つのレベルの階層であるので、過剰なことかもしれません。しかし私は間違っている可能性があります。 – rampion

+0

ええ - 私はそれに巻き込まれ、ページ上の例をもっと詳しく読んだ後でしか実現しませんでした。 –

関連する問題