Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.2k views
in Technique[技术] by (71.8m points)

ruby on rails 3.1 - (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

with these migrations:

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

If I attempt to create a Snapshot instance in rails console, using

Snapshot.new

I get

(Object doesn't support #inspect)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...