仍在学习Rails。 这个让我拔头发。
验证模型时,我试图使模型仅在7和14的days_in_week有效。
我有一个简单的模型:
class ScheduleRotum < ApplicationRecord
attr_accessor :start_date, :end_date, :days_in_week
validate :trial_trial
validates :days_in_week, presence: true
validates :days_in_week, inclusion: { in: [ 7,14 ] }
validates :days_in_week, numericality: true
def initialize(start_date: '', end_date: '', days_in_week: 7)
@start_date = start_date
@end_date = end_date
@days_in_week = days_in_week
end
def trial_trial
unless @days_in_week == 7 or @days_in_week == 14
errors[:base] << 'Wrong number of dates'
end
end
end
前三个验证有效。但是,包括数字变量在内的任何验证都将导致错误(在我尝试过的所有排列中):
2) ScheduleRotum#initialize days in week 15 is invalid
Failure/Error: expect(rotum).not_to be_valid
NoMethodError:
undefined method `[]' for nil:NilClass
这是该规范的代码:
require 'rails_helper'
RSpec.describe ScheduleRotum, type: :model do
context 'days in week' do
it 'is only valid as 7 or 14' do
rotum = ScheduleRotum.new days_in_week: 14
expect(rotum).to be_valid
expect(rotum.days_in_week).to eq 14
end
it '15 is invalid' do
rotum = ScheduleRotum.new days_in_week: 15
expect(rotum).not_to be_valid
end
end
end
我无法弄清楚为什么要使用数字验证来创建nilClass。有见识吗?