首页 > 解决方案 > 在允许 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

标签: ruby-on-railsrubyrspecmodelrspec-rails

解决方案


我认为它无效,因为它user_id是空的。我记得默认情况下,rails 会验证关联的存在。添加user_id到所有配置文件应该没问题


推荐阅读