【问题标题】:Why is the virtual attribute being set to null?为什么将虚拟属性设置为null?
【发布时间】:2011-09-18 20:58:16
【问题描述】:

我正在开发一个 ruby​​ on rails 注册/登录系统。

我有一个 ruby​​ on rails 表单,它有一个虚拟属性 - 密码。响应表单提交的操作更新模型对象并保存它。在保存 before_save: 回调之前调用 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" %>

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

【问题讨论】:

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


    【解决方案1】:

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

    instance.password
    

    在您认为相关的地方添加一些debugger 行并查看。

    【讨论】:

      猜你喜欢
      • 2011-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-02
      • 2010-09-24
      • 2022-06-16
      • 2018-01-28
      • 2014-08-25
      相关资源
      最近更新 更多