Rails: # do not show attribute

I define it @fooas an attribute of an instance of a class and using a callback after_initializeto set the value of this when creating / loading a record:

class Blog < ActiveRecord::Base
  @foo = nil

  after_initialize :assign_value

  def assign_value
    @foo = 'bar'
  end
end

However, when I am inspecta Blog object, I do not see the attribute @foo:

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

What do I need to do to include inspectin this? Or, conversely, how inspectdoes it determine what to output?

Thank.

+3
source share
1 answer

The active record determines which attributes should be displayed when checking based on the columns in the database table:

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

Picked up from base.rb on github

To change the output of a check, you will have to overwrite it with your own method, for example.

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

What should be output:

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

All Articles