Ruby on Rails - 字段设置为零

时间:2011-11-30 14:41:29

标签: ruby-on-rails ruby validation

为我的Ruby on Rails应用程序运行一个简单的自定义身份验证部分。当用户向应用程序注册时,我正在尝试发送电子邮件,但是当我尝试注册过程时,会在数据库中创建一条记录,但电子邮件设置为nil。这是一些代码:

我的模特:

class User < ActiveRecord::Base  
 attr_accessor :email, :password, :password_confirmation
 before_save :encrypt

 validates :password,
           :presence => true,
           :confirmation => true
 validates :email,
        :presence => true,
        :uniqueness => true,
        :format => { :with => /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\z$/ }

 def encrypt
   if password.present?
     self.password_salt = BCrypt::Engine.generate_salt
     self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
   end
 end

 def self.authenticate(email, password)
   user = find_by_email(email)
   if user && user.password_hash = BCrypt::Engine.hash_secret(password, user.password_salt)
     user
   else
     nil
   end
 end
end

我的控制器:

class UsersController < ApplicationController
  skip_filter :login_required, :only => [:create, :new]

  def new
    @user = User.new
    render :layout => 'unauthenticated'
  end

  def create
    @user = User.new(params[:user])
    @user.last_login = DateTime.now
    @user.is_active = true

    if @user.save
      session[:user_id] = @user.id

      redirect_to root_url
    else
      render :action => :new
    end
  end

end

观点:

<div id="register">
  <%= form_for @user do |f| %>
  <% if @user.errors.any? %>
    <div class="error">
      <ul>
        <% for message in @user.errors.full_messages %>
        <li><%= message %></li>
        <% end %>
      </ul>
    </div>
    <% end %>
    <ul>
      <li>
        <%= f.label :email %>
        <%= f.text_field :email %>
      </li>
      <li>
        <%= f.label :password %>
        <%= f.password_field :password %>
      </li>
      <li>
        <%= f.label :password_confirmation %>
        <%= f.password_field :password_confirmation %>
      </li>
      <li>
        <%= f.submit 'Register' %>
      </li>
    </ul>
  <% end %>
</div>

无论出于何种原因,每次用户注册时,电子邮件都会设置为nil。唯一看起来像处理电子邮件的是视图上的字段和验证,所以我不知道验证是否正在剥离它并且没有抛出任何错误。

:login_required方法位于我的application_controller中,并且是一个检查以确保用户已登录该会话。 skip_filter在进入登录和注册页面时不会检查。

有什么想法吗?提前谢谢。

1 个答案:

答案 0 :(得分:3)

你写过:

attr_accessor :email, :password, :password_confirmation

您是否尝试过删除此列表中的电子邮件参数?它可能会覆盖AR对电子邮件属性的持久性。您可能需要attr_accessible代替电子邮件。