为什么nil:尝试访问model.rb中的self.attribute时出现NilClass错误?

时间:2017-06-20 13:35:06

标签: ruby-on-rails scope

我正在尝试在date_of_birth模型上为Employee attr编写自己的验证,但我没有看到我的错误,我确定这是真的很糟糕而且在我的下面鼻子。代码如下,我的错误信息是;

 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

1 个答案:

答案 0 :(得分:3)

即使是第一次测试,您的自定义方法匹配器也会被调用,但self.date_of_birth实际上是nil,因此您会看到此错误。
在比较之前,您必须检查date_of_birth是否不是nil 如果您认为您的模型无效,您还必须add a new entryerrors集合 (另请检查您的情况,我使用>代替<来让您的考试成绩通过)

  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