我有设置表单。我想make,这样如果密码字段为空,则更新其他属性。 我也在使用 devise 。是否有一些有用的方法可以帮助我解决这个问题?
form.html.erb
<%= form_for(@user, :url => url_for(:controller => 'settings', :action => 'update')) do |f| %>
<%= f.label :email, 'Email' %>
<%= f.email_field :email %>
<%= f.label :mobile, 'Mobile' %>
<%= f.phone_field :mobile %>
<%= f.label :current_password, "Current password" %>
<%= f.password_field :current_password %>
<%= f.label :password, "New Password" %>
<%= f.password_field :password, :autocomplete => "off" %>
<%= f.label :password_confirmation, "Confirm New Password" %>
<%= f.password_field :password_confirmation %>
<%= f.submit "Update" %>
<% end %>
user.rb
validates :password, length: {minimum: 4}, on: :update, allow_blank: true
settings_controller.rb
def update
@user = current_user
if @user.update_attributes(user_params)
sign_in(@user, :bypass => true)
flash[:success] = "Settings were successfully updated"
respond_to do |format|
format.html {redirect_to :action=> :show}
end
else
flash[:fail] = "Settings **was not updated**"
respond_to do |format|
format.html {render :action => :show }
end
end
end
答案 0 :(得分:1)
使用此:
def update
# For Rails 4
account_update_params = devise_parameter_sanitizer.sanitize(:account_update)
# For Rails 3
# account_update_params = params[:user]
# required for settings form to submit when password is left blank
if account_update_params[:password].blank?
account_update_params.delete("password")
account_update_params.delete("password_confirmation")
end
@user = User.find(current_user.id)
if @user.update_attributes(account_update_params)
set_flash_message :notice, :updated
# Sign in the user bypassing validation in case his password changed
sign_in @user, :bypass => true
redirect_to after_update_path_for(@user)
else
render "edit"
end
end
这是来自设计维基的无耻复制粘贴,它包含许多您可以参考的有用信息 - wiki
答案 1 :(得分:0)
我也在使用devise并在admin命名空间中有一个从application_controller继承的users_controller,因为我想保持admin和user部分分开。 以下事情对我有用。
在用户模型中
验证:password,:password_confirmation,presence:true,on :: create
在控制器的更新操作中
def update # ..... @user.update_without_password(users_params) # ...... end