Rails:#inspect不显示属性

时间:2011-05-19 16:47:12

标签: ruby-on-rails ruby ruby-on-rails-3

我将@foo定义为类实例属性,并使用after_initialize回调设置创建/加载记录时的值:

class Blog < ActiveRecord::Base
  @foo = nil

  after_initialize :assign_value

  def assign_value
    @foo = 'bar'
  end
end

但是,当我inspect一个Blog对象时,我没有看到@foo属性:

 > Blog.first.inspect
=> "#<Blog id: 1, title: 'Test', created_at: nil, updated_at: nil>"

要让inspect包含此内容,我需要做些什么?或者相反,inspect如何确定要输出的内容?

感谢。

1 个答案:

答案 0 :(得分:5)

活动记录根据数据库表中的列确定要在inspect中显示的属性:

def inspect
  attributes_as_nice_string = self.class.column_names.collect { |name|
    if has_attribute?(name)
      "#{name}: #{attribute_for_inspect(name)}"
    end
  }.compact.join(", ")
  "#<#{self.class} #{attributes_as_nice_string}>"
end

取自base.rb on github

要更改检查的输出,您必须使用自己的方法覆盖它,例如

def inspect
  "#{super}, @foo = #{@foo}"
end

应该输出:

> Blog.first.inspect
=> "#<Blog id: 1, title: 'Test', created_at: nil, updated_at: nil>, @foo = 'bar'"