-1

我的任务是编写一个函数来验证下面代码中的名字和姓氏是否相同。我必须使用 ActiveModel::Validation 和 ActiveModel::Errors,如果两个名称相同,它应该给出错误消息“Nope”。

我的红宝石经验很少,但这是我的尝试:

require 'active_model'

class Person
    include ActiveModel::Validations
    validate :test
    validates_presence_of :first
    validates_presence_of :last

    def initialize(first, last)
        @first = first
        @last = last
    end

    def test
        errors.add_to_base("Nope") if @first == @last
    end

end

a = Person.new("James", "James")
b = Person.new("James")

因此,当我尝试实例化时收到一条错误消息,b但这只是一个 Ruby 错误,因为我的函数缺少参数。我敢肯定这可能很简单,但我会非常感谢任何帮助。

4

2 回答 2

0

检查https://github.com/rails/rails/tree/master/activemodel了解更多信息:

require 'active_model'

class TestValidator < ActiveModel::Validator
  def validate(record)
    record.errors[:base] = "First and last can't be the same" if record.first.presence == record.last.presence
  end
end

class Person
    include ActiveModel::Model

    attr_accessor :first, :last

    validates_presence_of :first, :last
    validates_with TestValidator
end

p = Person.new(first: "Nick", last: "Nick")
puts p.valid? # => false
puts p.errors.full_messages # => First and last can't be the same

p = Person.new(first: "Nick", last: "Doe")
puts p.valid? # => true
于 2013-10-15T15:30:44.500 回答
-1

我想出了自己的解决方案,我正在寻找的是:

require 'active_model'

class Person
include ActiveModel::Validations
attr_accessor :first, :last
validate :first_does_not_equal_last

def first_does_not_equal_last
  if @first == @last
    self.errors[:base] << "First cannot be the same as Last"
  end
end

def initialize(first, last)
    @first = first
    @last = last
end

end
于 2013-10-21T13:13:31.203 回答