【发布时间】:2020-04-26 13:13:40
【问题描述】:
对于这样的类,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 有这种区别?
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-4 activerecord rails-activerecord