【发布时间】:2017-06-20 13:35:06
【问题描述】:
我正在尝试为 Employee 模型上的 date_of_birth attr 编写自己的验证,但我看不出我哪里出错了,我确信这真的很愚蠢而且就在我的眼皮底下。代码如下,我的错误信息是;
NoMethodError:
undefined method `<' for nil:NilClass
员工.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
【问题讨论】:
标签: ruby-on-rails scope