如何在Rails中使用form_for仅更改模型中的一个属性

我想更改我的User模型的profile属性,它只是form_for中的一个字符串。 我遇到了一个问题,当我更新我的个人资料属性时,我的密码被设置为空白。

也就是说,我的用户帐户有密码,但是当我更改我的个人资料时,我的密码变为空白。 下次我尝试登录时,我只是将密码字段留空。

如何在不更改密码的情况下更改个人资料字段?

谢谢。

这是我下面的表格和更新动作。 我正在传递一个名为updating_password的隐藏字段,它是一个布尔值,用于是否需要密码validation和确认。

edit_profile.html.erb

 { :multipart => true } do |f| %>    "false" %>   

users_controller.rb

 def update @user = User.find(params[:id]) @user.updating_password = params[:user][:updating_password] #for updating profile only if(@user.updating_password == 'false') if @user.update_attribute('profile', params[:user][:profile]) redirect_to @user else @title = "Edit user" render 'edit' end end #for updating everything else including password if(@user.updating_password == 'true') if @user.update_attributes(params[:user]) redirect_to @user else @title = "Edit user" render 'edit' end end end 

我将从user.rb文件中添加相关的updates_password代码段:

 validates_presence_of :password, :if => :should_validate_password? validates_confirmation_of :password, :if => :should_validate_password? def should_validate_password? updating_password || new_record? end