为什么虚拟属性设置为null?

时间:2011-09-18 20:58:17

标签: ruby-on-rails ruby-on-rails-3 activerecord

我正在使用rails注册/登录系统上的ruby。

我在rails表单上有一个ruby,它有一个虚拟属性 - 密码。响应表单提交的操作会更新模型对象并保存它。在保存before_save之前:callback调用encrypt_password方法。但是,我不认为虚拟属性从表单中获取值。这是因为当我尝试登录时,它会反复失败。代码是:

 attr_accessor :password
 attr_accessible :Name, :password, :UserName, :RegistrationName, :BusinessName              

 before_save :encrypt_password

 def encrypt_password
   self.salt = make_salt 
   self.encrypted_password=encrypt(password)
 end

 def make_salt
   secure_hash("#{Time.now.utc}--#{password}")
 end

 def encrypt(string)
   secure_hash("#{salt}--#{string}")
 end

 def secure_hash(string)
   Digest::SHA2.hexdigest(string)
 end

好的,我检查过,是的,从表单中获取的密码为空。但我不明白为什么。这是表单的代码:

 <h1>This is the page of <%= @merchant.Name %> </h1>

<p>Please enter the password to be used </p>
<%= random_generator %>
<%= form_for @merchant,:url=>{:action=>'approve'} do |m| %>
<%= m.label :Name %><br/>
<%= m.text_field :Name %><br/>

<%= m.label :password %><br/>
<%= m.text_field :password %><br/>
<%= m.submit "Approve" %>

&lt;%end%&gt;

无论在密码字段中输入什么文本,都可以在控制器的“批准”操作中看到,如果我使用params [:merchant] [:password]直接打印它。但在模型中它是null

1 个答案:

答案 0 :(得分:1)

与任何attr_accessor一样,你可以通过以下方式获得它的价值:

instance.password

将一些debugger行放在您认为相关的位置并查看。

相关问题