您在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
谢谢Steve的回答。 – amaseuk 2010-11-09 10:06:05
我还发现了一个替代方案:attr_accessor_with_default:hello_world,“hello world” – amaseuk 2010-11-09 10:06:33
attr_accessor_with_default将在rails 3.1中弃用 – 2011-08-11 15:19:10