我有一个简单的案例,涉及两个模型类:
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
如果我尝试在rails控制台中创建快照实例,请使用
Snapshot.new
我得到了
(Object doesn't support #inspect)
现在是最好的部分。如果我注释掉snapshot.rb中的initialize方法,那么Snapshot.new就可以工作了。为什么会发生这种情况?
顺便说一句,我使用的是Rails 3.1和Ruby 1.9.2
发布于 2011-11-10 07:15:29
这是因为您重写了基类(ActiveRecord:: base )的initialize
方法。基类中定义的实例变量将不会初始化,#inspect
将失败。
要解决此问题,您需要在子类中调用super
:
class Game < ActiveRecord::Base
has_many :snapshots
def initialize(params={})
super(params)
# ...
end
end
发布于 2013-07-03 22:48:04
当我在这样的模型中进行序列化时,我出现了这种症状;
serialize :column1, :column2
需要像这样;
serialize :column1
serialize :column2
发布于 2019-06-04 13:47:42
在实现after_initialize
时也会发生这种情况,特别是当您试图访问select
中未包含的属性时。例如:
after_initialize do |pet|
pet.speak_method ||= bark # default
end
要修复此问题,请添加对该属性是否存在的测试:
after_initialize do |pet|
pet.speak_method ||= bark if pet.attributes.include? 'speak_method' # default`
end
https://stackoverflow.com/questions/7690697
复制相似问题