我创建了"新建/编辑用户"页面,以便管理员可以添加和更新用户。现在我正在尝试的是:当管理员编辑用户时,管理员可以选择不更新密码,只更新电子邮件。但是,保存更新后的电子邮件后,我将如何保留密码?
编辑页面:
<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
您可以检查密码字段是否为空,如果为空,则使用设备的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