我创建了新建/编辑用户页面,以便管理员可以添加和更新用户。现在我正在尝试的是:当管理员编辑用户时,管理员可以选择不更新密码,只更新电子邮件。但是在保存更新的电子邮件后如何保留密码?
编辑页面:
<div><%= f.label :email, 'Email Address' %>
<%= f.email_field :email, autofocus: true, :class => "form-control", autocomplete: "off", :placeholder => "Enter email address" %></div><br />
<div><%= f.label :password %>
<%= f.password_field :password, autocomplete: "off", :placeholder => "Enter password" %></div><br />
<div><%= f.label :password_confirmation %>
<%= f.password_field :password_confirmation, autocomplete: "off", :placeholder => "Confirm password" %></div><br />
型号:
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation
控制器:
def edit
@user = User.find(params[:id])
end
def update
@user = User.find(params[:id])
if @user.update_attributes(params[:user])
redirect_to edit_user_path
flash[:notice] = "User updated."
else
render :action => 'edit'
end
end
答案 0 :(得分:0)
你可以检查密码字段是否为空,如果它是空的,而不是使用设计的update_without_password
方法,试试这个
def update
@user = User.find(params[:id])
if params[:user][:password].blank?
if @user.update_without_password(params[:user].except(:password, :password_confirmation))
redirect_to edit_user_path
flash[:notice] = "User updated."
else
render :action => 'edit'
end
else
if @user.update_attributes(params[:user])
redirect_to edit_user_path
flash[:notice] = "User updated."
else
render :action => 'edit'
end
end
end