(对象不支持#inspect) [英] (Object doesn't support #inspect)

查看:194
本文介绍了(对象不支持#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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆