ruby-on-rails - 在允许 first_name 或 last_name 为空但不能同时为空的 Rails 上进行验证
问题描述
class Profile < ApplicationRecord
belongs_to :user
validate :first_or_last_name_null
def first_or_last_name_null
if first_name.nil? && last_name.nil?
errors.add(:base, "either first_name or last_name must be present!")
end
end
我不知道我的代码行有什么问题,从 rspec 得到以下错误。
分配 rq11 验证器:允许存在姓氏时名字为空的配置文件失败/错误:expect(Profile.new(:first_name =>nil, :last_name=>"Smith", :gender=>"male")).to be_valid 预期#<Profile id: nil, gender: "male", birth_year: nil, first_name: nil, last_name: "Smith", user_id: nil, created_at: nil, updated_at: nil>.valid?
返回 true,得到 false
规格文件有以下..
context "rq11" do
context "Validators:" do
it "does not allow a User without a username" do
expect(User.new(:username=> "")).to_not be_valid
end
it "does not allow a Profile with a null first and last name" do
expect(Profile.new(:first_name=>nil, :last_name=>nil, :gender=>"male")).to_not be_valid
end
it "allows a Profile with a null first name when last name present" do
expect(Profile.new(:first_name=>nil, :last_name=>"Smith", :gender=>"male")).to be_valid
end
it "allows a Profile with a null last name when first name present" do
expect(Profile.new(:first_name=>"Joe", :last_name=>nil, :gender=>"male")).to be_valid
end
it "does not allow a Profile with a gender other than male or female " do
expect(Profile.new(:first_name=>"first", :last_name=>"last", :gender=>"neutral")).to_not be_valid
end
it "does not allow a boy named Sue" do
expect(Profile.new(:first_name=>"Sue", :last_name=>"last", :gender=>"male")).to_not be_valid
end
it "allows a Profile with gender male" do
expect(Profile.new(:first_name=>"first", :last_name=>"last", :gender=>"male")).to be_valid
end
it "allows a Profile with gender female" do
expect(Profile.new(:first_name=>"first", :last_name=>"last", :gender=>"female")).to be_valid
end
end
end
解决方案
我认为它无效,因为它user_id
是空的。我记得默认情况下,rails 会验证关联的存在。添加user_id
到所有配置文件应该没问题
推荐阅读
- excel - 仅当两个不同单元格的日期不同时才运行 VBA
- android - 如何在 Android Studio 中将图片从一个活动发送到另一个活动
- python - Python Pandas 中重复的周和日期时间值
- python - 使用 django/html 中的静态文件进行下载给出 404
- java - 如何将相同对象类型列表中相同字段的值汇总为一个对象
- flutter - 如何正确使用 FutureBuilder?
- kubernetes - Minikube 入口没有响应
- javascript - 将几个变量传递给函数 Jquery
- c++ - 使用带有结构不完整类型错误的模板
- c# - 何时使用全局变量(减少全局变量 vs DRY)