2010-11-09 118 views
0

我無法賦值在after_initialize方法的虛擬屬性:after_initialize虛擬屬性

attr_accessor :hello_world 

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

在我看來文件:

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

這並不返回任何輸出。
您是否有任何建議或替代方法爲虛擬屬性設置默認值?

回答

4

您在after_initialize回調中使用了一種奇怪的分配方法。你只需要分配給self.hello_world甚至@hello_world。您的任務在類的實例中創建了一個哈希值,其中鍵爲:hello_world,值與預期值相同。在你看來,你可以參考@mymodel [:hello_world],但這遠非慣用。

以下示例模型和控制檯會話顯示了使用各種初始化虛擬屬性的方法的效果。

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

謝謝Steve的回答。 – amaseuk 2010-11-09 10:06:05

+3

我還發現了一個替代方案:attr_accessor_with_default:hello_world,「hello world」 – amaseuk 2010-11-09 10:06:33

+0

attr_accessor_with_default將在rails 3.1中棄用 – 2011-08-11 15:19:10