我创建了一个示例应用程序,但在编辑字段时遇到了问题。每当我尝试更新我的字段时,它都会在我的用户模型中触发我的“验证:password_confirmation”,即使我没有在页面中包含密码确认字段。
以下是我的一些代码:
这是我显示数据的“pages/services.html.erb”
<h1>Shows all users</h1>
<% if current_user %>
<table border="1">
<% @column_names.each do |column_name| %>
<% if column_name == "name" || column_name == "username" || column_name == "email"%>
<td>
<strong><%= column_name.capitalize %></strong>
</td>
<% end %>
<% end %>
<% @users.each do |user| %>
<tr>
<td><%= user.name%></td>
<td><%= user.username%></td>
<td><%= user.email%></td>
<td><%= link_to "edit", edit_user_path(user)%></td>
<td><%= link_to "delete", '#'%></td>
</tr>
<%end%>
</table>
<% end %>
这是我的'users/edit.html.erb'。我有一个用户模型仅供参考。
编辑
<%= form_for @user do |f| %>
<%= render 'shared/error_message' %>
<p>
<%= f.text_field :name%><br/>
<%= f.label :name %><br/>
</p>
<p>
<%= f.text_field :username %><br/>
<%= f.label :username%><br/>
</p>
<p>
<%= f.email_field :email%><br/>
<%= f.label :email %><br/>
</p>
<p> <%= f.submit "Update" %></p>
<% end%>
这是我的 UsersController 代码:
class UsersController < ApplicationController
def new
@user = User.new
@title = "User Sign Up"
end
def create
@user = User.new(params[:user])
if @user.save
sign_in_check @user
redirect_to root_path, :flash => { :success => "Welcome to the Bakeshop"}
else
@title = "User Sign Up"
render 'new'
end
end
def edit
@user = User.find(params[:id])
end
def update
@user = User.find(params[:id])
if @user.update_attributes(params[:user])
redirect_to pages_services_path, :notice => "Update Successful"
else
render "edit"
end
end
end
有人可以解释这种现象并提出解决方案吗?
编辑
添加了我的 user.rb 文件代码:
class User < ActiveRecord::Base
require 'digest/md5'
attr_accessible :password_confirmation, :name, :email, :password, :username
before_save :encrypt_password
validates :name, :presence => true,
:length => { :maximum => 25}
validates :username, :presence => true,
:length => { :maximum => 25},
:uniqueness => {:case_sensitive => false}
validates :email, :presence => true,
:uniqueness => {:case_sensitive => false}
validates :password, :presence => true,
:confirmation => true,
:length => {:within => 6..40}
validates :password_confirmation, :presence => true
def self.authenticate(username, password)
user = User.find_by_username(username)
if user && user.password == Digest::MD5.hexdigest(password)
user
else
nil
end
end
def encrypt_password
self.password = Digest::MD5.hexdigest(password)
end
end