-1

私は、以下のコードで名と姓が同じでないことを検証する関数を書くことを任されました。ActiveModel::Validation と ActiveModel::Errors を使用する必要があり、2 つの名前が同じ場合は、エラー メッセージ "いいえ" が表示されます。

私はルビーの経験がほとんどありませんが、ここに私の試みがあります:

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 に答える