2011-10-07 83 views
5

我有一个简单的例子,涉及到两个模型类:(对象不支持#inspect)

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中的初始化方法,那么Snapshot.new将起作用。这是为什么发生?
顺便说一句我正在使用Rails 3.1和Ruby 1.9.2

+0

虽然它可能不是你的问题,但是当自定义“检查”方法中出现错误时会出现此问题。原始错误不可见,这可能很烦人。 –

回答

9

发生这种情况是因为您覆盖了基类(ActiveRecord :: Base)的initialize方法。在您的基类中定义的实例变量将不会被初始化,并且#inspect将会失败。

为了解决这个问题,你需要调用super在你的子类:

class Game < ActiveRecord::Base 
    has_many :snapshots 

    def initialize(params={}) 
    super(params) 
    # ... 
    end 
end 
+0

为什么你将params传递给super? ActiveRecord :: Base会用它做什么? –

0

我不知道确切原因,但我得到了,当我不小心拼错“belongs_to的”作为“belong_to”这个错误相关的类定义。

7

我有这样的症状,当我有一个像这样的模型序列化;

serialize :column1, :column2 

需要像;

serialize :column1 
serialize :column2 
+0

我写了'serialize:description,Array'不当(如'serialize:description,:array') – lakesare