在rails中验证两个值必须!= nil

时间:2016-10-29 20:10:36

标签: ruby-on-rails ruby validation

我必须在RoR模型中设置验证,仅在first_name和last_name中的一个不为空时才通过。它通过了前两个测试

 1) Assignment rq11 Validators: allows a Profile with a null first name when last name present
 Failure/Error: expect(Profile.new(:first_name=>nil, :last_name=>"Smith", :gender=>"male")).to be_valid
   expected `#<Profile id: nil, gender: "male", birth_year: nil, first_name: nil, last_name: "Smith", user_id: nil, created_at: nil, updated_at: nil>.valid?` to return true, got false
 # ./spec/assignment_spec.rb:290:in `block (4 levels) in <top (required)>'
 # ./spec/assignment_spec.rb:12:in `block (2 levels) in <top (required)>'

但是下一个测试会收到一条错误消息

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

规格

class Profile < ActiveRecord::Base
  belongs_to :user
  validates :gender, inclusion: {in: %w(male, female), message: "Must be male or female"}
  validate :first_or_last_name



  def first_or_last_name
    if first_name  && last_name == nil
      errors.add(:first_name, "Cannot be both nil")
    end
  end

end

模型

{
  "userMessage" : "ErnollmentSuccess",
  "data" : {
    "memberId" : 3635,
    "refreshToken" : "fc22418f1267488485e5f99a510b1618",
    "tokenType" : "bearer",
    "accessToken" : "1ce9744bd2604392adc0e896bba24f2a",
    "expiresIn" : 1209600
}

逻辑运算符有问题吗?

3 个答案:

答案 0 :(得分:3)

我会写这样的验证:

def first_or_last_name
  if first_name.blank? && last_name.blank?
    errors.add(:first_name, "cannot be both blank")
  end
end

此外,您在gender验证程序的定义中输入了拼写错误。从%w(male, female)中删除逗号。 %w语法生成一个字符串数组,不需要逗号。目前它只允许"male,""female"。将其更改为:

validates :gender, inclusion: { in: %w(male female), 
                                message: "Must be male or female"}

答案 1 :(得分:2)

您的代码检查是否已定义first_name且last_name为nil。

if first_name && last_name == nil

相当于

if first_name && (last_name == nil)

https://ruby-doc.org/core-2.2.0/doc/syntax/precedence_rdoc.html。 ==来自&amp;&amp;

你可以尝试:

if (first_name || last_name) == nil

if first_name.nil? and last name.nil?

unless first_name or last_name

最后,您可能不希望定义两个名称但是为空,所以:

if first_name.blank? and last_name.blank?

答案 2 :(得分:2)

以下验证器是问题所在。

validates :gender, inclusion: {in: %w(male, female), message: "Must be male or female"}