2017-06-20 12 views
2

我想在Employee模型上寫一個date_of_birth attr我自己的驗證,我沒有看到我的錯誤,我敢肯定這是真正愚蠢的,在我的鼻子下面。代碼如下,我的錯誤信息是;爲什麼nil:試圖訪問model.rb中的self.attribute時發生NilClass錯誤?

NoMethodError: 
    undefined method `<' for nil:NilClass 

employee.rb

class Employee < ApplicationRecord 
    belongs_to :quote 

    validates_presence_of :first_name, :last_name, :email, :gender, :date_of_birth, :salary 
    validates :first_name, length: { minimum: 2, message: "minimum of 2 chars" } 
    validates :last_name, length: { minimum: 2, message: "minimum of 2 chars" } 
    validates_email_format_of :email, :message => 'incorrect email format' 
    validate :older_than_16 

    enum gender: [ :m, :f ] 

    private 

    def older_than_16 
     self.date_of_birth < Time.now-16.years 
    end 

end 

schema.rb

ActiveRecord::Schema.define(version: 20170620125346) do 

    # These are extensions that must be enabled in order to support this database 
    enable_extension "plpgsql" 

    create_table "employees", force: :cascade do |t| 
    t.string "first_name" 
    t.string "last_name" 
    t.string "email" 
    t.string "initial" 
    t.integer "gender" 
    t.date  "date_of_birth" 
    t.integer "salary" 
    t.integer "quote_id" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
    t.index ["quote_id"], name: "index_employees_on_quote_id", using: :btree 
    end 

employee_spec.rb

RSpec.describe Employee, type: :model do 
    describe 'validations' do 

     it { should validate_presence_of(:date_of_birth) } 
     it { should_not allow_value(Date.today-15.years).for(:date_of_birth) } 
     # it { should allow_value(Date.today-17.years).for(:date_of_birth) } 
    end 
end 

回答

3

您的自定義方法匹配甚至第一次測試,但self.date_of_birth叫實際上是nil所以你看到這個錯誤。
在比較之前,您必須檢查date_of_birth是否不是nil
如果您認爲模型無效,您還必須將add a new entry設置爲errors集合。
(還要檢查你的情況,我用>,而不是<,讓您的測試通過)

def older_than_16 
     return if self.date_of_birth.nil? 
     if self.date_of_birth > Time.now-16.years 
      errors.add(:date_of_birth, "Should be at least 16 years old") 
     end 
    end 
+0

感謝@ Aschen,現在完美的作品。但我不明白「self.date_of_birth」是如何從零開始的?存在被驗證並通過測試?它是如何零?感謝您在這裏幫助我 – jbk

+0

我不知道'should-matcher'如何在內部工作,但我認爲'it {validate_presence_of(:date_of_birth)}'嘗試通過傳遞'nil'值來檢查存在驗證,除了模型將爲'model.valid?'返回false – Aschen

相關問題