(对象不支持#inspect)

问题描述 投票:0回答:12

我有一个简单的案例,涉及两个模型类:

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

如果我尝试在 Rails 控制台中创建快照实例,请使用

Snapshot.new

我明白了

(Object doesn't support #inspect)

现在是好的部分。如果我注释掉 snapshot.rb 中的初始化方法,那么 Snapshot.new 就可以工作。为什么会出现这种情况?
顺便说一句,我正在使用 Rails 3.1 和 Ruby 1.9.2

ruby-on-rails-3.1 ruby-1.9.2
12个回答
10
投票

发生这种情况是因为您重写了基类 (ActiveRecord::Base) 的

initialize
方法。基类中定义的实例变量将不会被初始化,并且
#inspect
将失败。

要解决此问题,您需要在子类中调用

super

class Game < ActiveRecord::Base
  has_many :snapshots

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

8
投票

当我在这样的模型中进行序列化时,我出现了这种症状;

serialize :column1, :column2

需要像;

serialize :column1
serialize :column2

7
投票

当我在

joins
中使用无效的关联名称时,我遇到了这个问题。

例如,

Book.joins(:authors).first

应该是

Book.joins(:author).first

假设 Book 模型

belongs_to
Author 模型。


3
投票

当您实现

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

1
投票

我不确定具体原因,但当我不小心将关联的类定义中的“belongs_to”拼写为“belong_to”时,出现了此错误。


1
投票

我相信你忘记了

rails db:migrate

0
投票

尝试调用.valid?在新对象上看看是否可以获得更有用的错误。

就我而言,我从一段代码中收到此错误,该代码创建我的模型之一的新实例并向其字段分配值。事实证明,我的代码正在为 Rails 无法与该字段类型匹配的字段之一分配一个值。打电话有效吗?在新对象上给了我一个更有用的错误(#的未定义方法“to_f”

这是一个误导性且非特异性的错误。例如,我刚刚得到它是因为我制作了这样的范围:

scope :posted, -> { where('posted_on_date <= ?', Date.today) }

当它应该是:

scope :posted, -> { where('post_on_date <= ?', Date.today) }

就我而言,这是由于我错误地使用了

posted_on_date
属性。


0
投票

0
投票

如果模型包含

after_find
,我就会遇到此问题。


0
投票

如果属性类型写错也会出现同样的错误:

attribute :publicar, :integer, default: true

而不是

attribute :publicar, :boolean, default: true

0
投票

我在运行 ActiveRecord

.where
子句/方法时收到此错误。

只是因为栏目名称有错别字。一旦我修复了拼写错误,查询就完全按照预期工作了。

错误:

Package.where(scrape_nunber: 2)

对(修复了列名称中的拼写错误,现在可以使用):

Package.where(scrape_number: 2)

只需仔细检查 where 子句中的列名称没有拼写错误。


0
投票

我在尝试将设备身份验证与现有用户模型集成后遇到了这个问题,我通过运行下面的命令解决了它:

spring stop

不知道确切原因,但希望对某人有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.