全新的rails在这里。我正在尝试使用密码和散列算法实现用户身份验证系统。现在,当我尝试创建新用户时,用户的密码属性始终为零。
这是我的用户/新视图:
<% @page_title = 'New Users' %>
<div class="user new">
<h2>Create User</h2>
<%= form_for(:user, :url => {:action => 'create'}) do |f| %>
<%= render(:partial => 'form', :locals => {:f => f} ) %>
<div class="form-buttons">
<%= submit_tag('Create User') %>
</div>
<% end %>
</div>
<%= link_to 'Back', users_path %>
还有我的部分布局_form:
<% if @user.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@user.errors.count, "error") %> prohibited this user from being saved:</h2>
<ul>
<% @user.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<table summary="Admin user form fields">
<tr>
<th><%= f.label(:first_name) %></th>
<td><%= f.text_field(:first_name) %></td>
</tr>
<tr>
<th><%= f.label(:last_name) %></th>
<td><%= f.text_field(:last_name) %></td>
</tr>
<tr>
<th><%= f.label(:email) %></th>
<td><%= f.text_field(:email) %></td>
</tr>
<tr>
<th><%= f.label(:password) %></th>
<td><%= f.text_field(:password) %></td>
</tr>
</table>
但是,当我们到达控制器时,@user.password 始终为零。为什么 :password 表单的值没有被传递?来自控制器的代码:
def create
@user = User.new(user_params)
flash[:notice] = "Password: " + @user.password #ALWAYS NIL
respond_to do |format|
if @user.save
format.html { redirect_to @user, notice: 'User was successfully created.' }
format.json { render action: 'show', status: :created, location: @user }
else
format.html { render action: 'new' }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
密码是模型中的 attr_accessor。这是模型代码:
class User < ActiveRecord::Base
attr_accessor :password #not value in database, only in model
validates_length_of :password, :within => 6..25, :on => :create
before_save :create_hashed_password
after_save :clear_password
def self.hash_with_salt(password= "", salt="")
Digest::SHA1.hexdigest("Put #{salt} on the #{password}")
end
#makes a salt for encription using the user's email (unique) and time (random)
def self.make_salt(email="")
Digest::SHA1.hexdigest("Use #{email} with #{Time.now} 2 make salt")
end
#will return user if login is successful else returns fasle
def self.authenticate(email="", password="")
user = User.find_by_email(email)
if user && user.password_match?(password)
return user
else
return false
end
end
#The same password string with the same hash method should always generate
#the same hashed_password
def password_match?(password="")
hashed_password == User.hash_with_salt(password, salt)
end
private
def create_hashed_password
#Whenever :password has a value, hashing is needed
unless password.blank?
self.salt = User.make_salt(username) if salt.blank?
self.hashed_password = User.hash_with_salt(password, salt)
end
end
def clear_password
self.password = nil
end
end
在此先感谢您的帮助。