gpt4 book ai didi

ruby - ActiveRecord - 未定义的方法 'match'

转载 作者:数据小太阳 更新时间:2023-10-29 07:43:31 25 4
gpt4 key购买 nike

我试图在我的记录中编码一个简单的层次结构,但我遇到了一个奇怪的错误。

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

如果我将 has_many :children, :class_name => Foo, :as => :parent 添加到 Foo 的定义中,而不是执行 quux = bar.children.create(name => 'Quux') 我遇到了类似的错误。

我做错了什么?

最佳答案

belongs_to:class_name 选项需要一个字符串,而不是一个类。

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

您可能还想考虑使用 acts_as_tree 或其他一些专为处理此类层次结构而设计的插件(有很多;我不记得目前最喜欢的是什么);它可能会让你的生活更轻松。

关于ruby - ActiveRecord - 未定义的方法 'match',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6848879/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com