(对象不支持#inspect) [英] (Object doesn't support #inspect)
问题描述
我有一个简单的案例,涉及两个模型类:
I have a simple case, involving two model classes:
class Game < ActiveRecord::Base
has_many :snapshots
def initialize(params={})
# ...
end
end
class Snapshot < ActiveRecord::Base
belongs_to :game
def initialize(params={})
# ...
end
end
这些迁移:
class CreateGames < ActiveRecord::Migration
def change
create_table :games do |t|
t.string :name
t.string :difficulty
t.string :status
t.timestamps
end
end
end
class CreateSnapshots < ActiveRecord::Migration
def change
create_table :snapshots do |t|
t.integer :game_id
t.integer :branch_mark
t.string :previous_state
t.integer :new_row
t.integer :new_column
t.integer :new_value
t.timestamps
end
end
end
如果我尝试使用
Snapshot.new
我知道
(Object doesn't support #inspect)
现在好了.如果我在snapshot.rb中注释掉了initialize方法,那么Snapshot.new就可以了.为什么会这样?
顺便说一句,我正在使用Rails 3.1和Ruby 1.9.2
Now for the good part. If I comment out the initialize method in snapshot.rb, then Snapshot.new works. Why is this happening?
BTW I am using Rails 3.1, and Ruby 1.9.2
推荐答案
之所以发生这种情况,是因为您覆盖了基类(ActiveRecord :: Base)的initialize
方法.在基类中定义的实例变量将不会初始化,并且#inspect
将失败.
This is happening because you override the initialize
method of your base class (ActiveRecord::Base). Instance variables defined in your base class will not get initialized and #inspect
will fail.
要解决此问题,您需要在子类中调用super
:
To fix this problem you need to call super
in your sub class:
class Game < ActiveRecord::Base
has_many :snapshots
def initialize(params={})
super(params)
# ...
end
end
这篇关于(对象不支持#inspect)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!