我有一个带有名称和密码属性的用户模型。当用户单击“编辑”时,我只希望名称字段可编辑和验证,而不是密码字段。当用户单击“重置密码”时,反之亦然。我认为我的主要问题是如何在名称字段编辑期间关闭密码验证以及如何在密码编辑期间关闭名称验证?
编辑.html.erb
<%= form_for @user, html: { class: "form_settings" } do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<p><span><%= f.label :name %></span>
<%= f.text_field :name %>
</p>
<p style="padding-top: 15px"><span> </span>
<%= f.submit "Submit", class: "submit" %>
</p>
<% end %>
reset_password.html.erb
<%= form_for @user, html: { class: "form_settings" } do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<p><span><%= label_tag :old_password, "Current Password" %></span>
<%= password_field_tag :old_password %>
</p>
<p><span><%= f.label :password %></span>
<%= f.password_field :password %>
</p>
<p><span><%= f.label :password_confirmation %></span>
<%= f.password_field :password_confirmation %>
</p>
<p style="padding-top: 15px"><span> </span>
<%= f.submit "Submit", class: "submit" %>
</p>
<% end %>
users_controller.rb
def update
@user = User.find(params[:id])
if params[:old_password]
if @user.authenticate(params[:old_password])
@user.update_attributes(password: params[:user][:password])
flash[:success] = "Password has been updated"
redirect_to @user
else
flash.now[:error] = "Current password is incorrect"
render :reset_password
end
elsif @user.update_attributes(params[:user])
flash[:success] = "User name updated"
redirect_to @user
else
render :edit
end
end
我的另一个问题是密码和密码确认验证不起作用。这就是我在模型中的内容:
validates :password, presence: true, confirmation: true
更新 获得了要重置的密码并使用此代码进行验证:
def update
@user = User.find(params[:id])
if params[:old_password]
if @user.authenticate(params[:old_password])
if params[:user][:password] == params[:user][:password_confirmation]
@user.update_attributes(password: params[:user][:password])
flash[:success] = "Password has been updated"
redirect_to @user
else
flash.now[:error] = "Passwords don't match"
render :reset_password
end
else
flash.now[:error] = "Current password is incorrect"
render :reset_password
end
elsif @user.update_attributes(params[:user])
flash[:success] = "User name updated"
redirect_to @user
else
render :edit
end
end
但这对我来说似乎太复杂了。有人看到更简单的解决方案吗?
但是我仍然有编辑名称字段的问题。就是说密码不能为空。