开发者

after_initialize virtual attribute

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开发者_JS百科 a virtual attribute?


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜