(Object does not 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 transitions:

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 try to create an instance of Snapshot in the 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

+6
source share
4 answers

This is because you are overriding the method of initializeyour base class (ActiveRecord :: Base). The instance variables defined in your base class will not be initialized, but #inspectwill fail.

, super :

class Game < ActiveRecord::Base
  has_many :snapshots

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

, :

serialize :column1, :column2

:

serialize :column1
serialize :column2
+8

, , , "" "" .

0

, 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
0

All Articles