我有设置表单。我想要make,以便如果密码字段为空,则更新其他属性。此外,我正在使用设计。有没有一些有用的方法可以帮助我?
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
设置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
使用此:
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
这是从设计维基无耻的复制粘贴,它包含了很多有用的信息,你可以参考-维基
我还在admin命名空间中使用design和继承自application_controller的users_controller,因为我想将admin和user部分分开。以下内容对我有效。
在用户模型中
验证:password,:password_confirmation,presence:true,on::create
在控制器的更新操作中
def update # ..... @user.update_without_password(users_params) # ...... end