【问题标题】:ActiveModel::Errors shows different output for to_h and to_hashActiveModel::Errors 显示 to_h 和 to_hash 的不同输出
【发布时间】:2020-04-26 13:13:40
【问题描述】:

对于这样的类,ActiveRecord::Errorsto_hto_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_hto_hash 有这种区别?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 activerecord rails-activerecord


    【解决方案1】:

    它们并不完全相同,'to_hash' 是隐式转换,而 'to_h' 是显式转换。
    隐式转换为您提供详细的数据类型,并且在转换过程中数据不会丢失。但是,如果您只想要基本数据,只需使用 'to_h' 或显式即可。

    参考:implicit-vs-expicit

    【讨论】:

      猜你喜欢
      • 2012-06-26
      • 1970-01-01
      • 2021-06-14
      • 1970-01-01
      • 1970-01-01
      • 2019-12-04
      • 2019-04-21
      相关资源
      最近更新 更多