Ruby 2.1.0有效吗?工作不正常

时间:2014-02-13 15:14:03

标签: ruby-on-rails ruby

我正在使用rails 4.0.2和Ruby 2.1.0。我想知道 有效吗? 方法中有错误吗?我在我的rails控制台中得到了以下输出,它处于测试模式:

2.1.0 :018 > e1
 => #<Employer id: 3, first_name: "Test 2", last_name: "Case", email: "abc@d.sun", created_at: "2014-02-13 11:53:35", updated_at: "2014-02-13 11:53:35", password_digest: "$2a$04$JfCeRCMUESYgDGoBerqaZ.jEuEnyWPqrZ4K6L/sSOzsD..."> 
2.1.0 :019 > e1.valid?
  Employer Exists (2.7ms)  SELECT 1 AS one FROM "employers" WHERE (LOWER("employers"."email") = LOWER('abc@d.sun') AND "employers"."id" != 3) LIMIT 1
=> false

在SQL中它说:

"employers"."id" != 3  

不应该吗?

"employers"."id" = 3

考虑到雇主的身份证是3。

但是,我可以验证同一个雇主。那么我的控制器或型号有问题吗?好吧,我很困惑。

2.1.0 :020 > e1.authenticate( "foobar" )
 => #<Employer id: 3, first_name: "Test 2", last_name: "Case", email: "abc@d.sun", created_at: "2014-02-13 11:53:35", updated_at: "2014-02-13 11:53:35", password_digest: "$2a$04$JfCeRCMUESYgDGoBerqaZ.jEuEnyWPqrZ4K6L/sSOzsD..."> 

控制器

class EmployersController < ApplicationController
  def new

    @employer = Employer.new(employer_params)
    if @employer.save

      redirect_to @employer
    else
      render 'new'
    end
  end

  def update
    if @employer.update_attributes(employer_params)
      redirect_to @employer
    else
      render 'edit'
    end
  end
  private
    def employer_params
      params.require(:employer).permit(:first_name, :last_name, :email, :password, :password_confirmation )
    end
end

模型

class Employer < ActiveRecord::Base

    has_secure_password

    validates :first_name, presence: true, length: { maximum: 50 }
    validates :last_name, presence: true, length: { maximum: 50 }

    VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i

    validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, 
                uniqueness: { case_sensitive: false }

    before_save { self.email = email.downcase! }


    validates :password, length: { minimum: 6 }

end

2 个答案:

答案 0 :(得分:3)

不,它正在寻找具有相同电子邮件的其他记录,因为您希望它是唯一的。

答案 1 :(得分:2)

这是一个唯一性验证,使用相同的电子邮件查询数据库中的其他记录。