Для такого класса, ActiveRecord::Errors
для to_h
и to_hash
дает два разных вывода, хотя они являются псевдонимами друг друга.
class Person
# Required dependency for ActiveModel::Errors
extend ActiveModel::Naming
def initialize
@errors = ActiveModel::Errors.new(self)
end
attr_accessor :name, :phone, :age
attr_reader :errors
def validate!
errors.add(:name, :blank, message: "Name cannot be nil") if name.nil?
errors.add(:name, :blank, message: "Name is mandatory") if name.nil?
errors.add(:phone, :blank, message: "Phone cannot be nil") if phone.nil?
end
# The following methods are needed to be minimally implemented
def read_attribute_for_validation(attr)
send(attr)
end
def self.human_attribute_name(attr, options = {})
attr
end
def self.lookup_ancestors
[self]
end
end
person = Person.new()
person.validate!
person.errors.message => {:name=>["can't be blank", "can't be blank"], :phone=>["can't be blank"]}
person.to_hash => {:name=>["can't be blank", "can't be blank"], :phone=>["can't be blank"]}
person.to_h => {:name=>"can't be blank", :phone=>"can't be blank"}
Почему эта разница между to_h
и to_hash
для этого класса?