2010-11-09 138 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