Ruby on rails 初始化后的Rails
我有以下课程:Ruby on rails 初始化后的Rails,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,我有以下课程: class Question < ActiveRecord::Base serialize :choices attr_accessible :content, :choices, :answer_id after_initialize :after_initialize private def after_initialize choices ||= ['','','',''] end end 因此,基本上,:choice
class Question < ActiveRecord::Base
serialize :choices
attr_accessible :content, :choices, :answer_id
after_initialize :after_initialize
private
def after_initialize
choices ||= ['','','','']
end
end
因此,基本上,:choices
属性没有正确初始化。事实上,检查@question
可以得出以下结论:
#<Question id: nil, content: nil, choices: nil, answer_id: nil, created_at: nil, updated_at: nil>
#
我希望其他一切都是零,但我希望
:choices
是['','','','',]
。我的计时错误吗?初始化后的中的以下代码正在更新选项
局部变量,这不是您想要的:
choices ||= ['','','','']
你需要使用
self.choices || = ['','','','']
如中所述,您很接近。设置属性时,名称不够。使用self.
前缀使其工作:
self.choices ||= ['','','','']
只使用选项
创建该名称的局部变量,而不是设置属性。尝试在初始化后更改函数的名称
self.choices || = ['','','','']
self.choices ||= ['','','','']