0

I am unable to assign a value to a virtual attribute in the after_initialize method:

attr_accessor :hello_world

def after_initialize
   self[:hello_world] = "hello world"
end

In my view file:

hello world defaulted? <%= @mymodel.hello_world %>

This doesn't return any output.
Do you have any suggestions or any alternative to set up a default value for a virtual attribute?

amaseuk
  • 2,147
  • 4
  • 24
  • 43

1 Answers1

4

You are using an odd method of assignation within your after_initialize callback. You just need to assign to self.hello_world or even @hello_world. Your assignment has created a hash within your instance of the class with a key of :hello_world and the value as expected. Within your view you could reference @mymodel[:hello_world] but this is far from idiomatic.

The following example model and console session shows the effect of using various methods of initializing the virtual attribute.

class Blog < ActiveRecord::Base

  attr_accessor :hello_world1, :hello_world2, :hello_world3

  def after_initialize
    self.hello_world1 = "Hello World 1"
    self[:hello_world2] = "Hello World 2"
    @hello_world3 = "Hello World 3"
  end
end


ruby-1.9.2-p0 > b=Blog.new
 => #<Blog id: nil, title: nil, content: nil, created_at: nil, updated_at: nil> 
ruby-1.9.2-p0 > b.hello_world1
 => "Hello World 1" 
ruby-1.9.2-p0 > b.hello_world3
 => "Hello World 3" 
ruby-1.9.2-p0 > b.hello_world2
 => nil 
ruby-1.9.2-p0 > b[:hello_world2]
 => "Hello World 2" 
ruby-1.9.2-p0 > b[:hello_world1]
 => nil
Steve Weet
  • 28,126
  • 11
  • 70
  • 86