(Object doesn't support #inspect)

假如想象 提交于 2019-12-01 02:09:02

问题


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


回答1:


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



回答2:


I had this symptom when I had a serialize in a model like this;

serialize :column1, :column2

Needs to be like;

serialize :column1
serialize :column2



回答3:


This can also happen when you implement after_initialize, particularly if you are attempting to access attributes which were not included in your select. For instance:

after_initialize do |pet|
  pet.speak_method ||= bark  # default
end

To fix, add a test for whether the attribute exists:

after_initialize do |pet|
  pet.speak_method ||= bark if pet.attributes.include? 'speak_method'  # default`
end



回答4:


I'm not sure exactly why, but I got this error when I accidentally misspelled 'belongs_to' as 'belong_to' in the associated class definition.



来源:https://stackoverflow.com/questions/7690697/object-doesnt-support-inspect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!