How to only change one attribute in a model using form_for in Rails

帅比萌擦擦* 提交于 2019-12-11 20:46:58

问题


I want to change my User model's profile attribute which is just a string in a form_for. I am running into a problem where my password is getting set to blank when I update my profile attribute.

That is, my user account has a password, but when I change my profile, my password becomes blank. The next time I try to log in, I just leave the password field blank.

How do I change my profile field without changing my password?

Thanks.

Here is my form below and update action. I'm passing a hidden field called updating_password which is a boolean for whether or not password validation and confirmation is required.

edit_profile.html.erb

<%= form_for @user, :html => { :multipart => true } do |f| %>

  <%= f.label :profile %>
  <%= f.text_area :profile%>

  <%= f.hidden_field :updating_password, :value => "false" %>

  <%= submit_tag "update" %>

<% end %>

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

I'll add the relevant updating_password snippet from my user.rb file:

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

来源:https://stackoverflow.com/questions/10566865/how-to-only-change-one-attribute-in-a-model-using-form-for-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!