Rails - Monkey-patch rails full_messages

时间:2016-03-20 15:46:17

标签: ruby-on-rails activerecord monkeypatching

当我不知道属性(Rails adding error to :base not working as expected)时,我一直很难看到显示属性的rails错误消息。

我发现了一个可以修补完整邮件的网站,因此您可以显示错误消息而不显示属性http://adamhooper.com/eng/articles/5

然而,这是相当陈旧的,自那时以来,rails已发生变化。我想知道是否可以在rails 4.2中制作相同的猴子补丁。

full_messages方法以前定义为:

...
    def full_messages(options = {})
      full_messages = [] 

      @errors.each_key do |attr|
        @errors[attr].each do |message|
          next unless message

          if attr == "base"
            full_messages << message
          else 
            attr_name = @base.class.human_attribute_name(attr)
            full_messages << attr_name + I18n.t('activerecord.errors.format.separator', :default => ' ') + message 
          end  
        end  
      end  
      full_messages
    end

和补丁:

if RAILS_GEM_VERSION =~ /^2\.3/
  ActiveRecord::Errors.class_eval do
    # Remove complicated logic
    def full_messages
      returning full_messages = [] do
        @errors.each_key do |attr|
          @errors[attr].each do |msg|
            full_messages << msg if msg 
          end 
        end 
      end 
    end 
  end 
end

目前的方法是:

# File activemodel/lib/active_model/errors.rb, line 348
    def full_messages
      map { |attribute, message| full_message(attribute, message) }
    end

# File activemodel/lib/active_model/errors.rb, line 369
    def full_message(attribute, message)
      return message if attribute == :base
      attr_name = attribute.to_s.tr('.', '_').humanize
      attr_name = @base.class.human_attribute_name(attribute, :default => attr_name)
      I18n.t(:"errors.format", {
        :default   => "%{attribute} %{message}",
        :attribute => attr_name,
        :message   => message
      })
    end

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您也可以将字段转换为空字符串。 Rails将在

中找到它
en:
  activemodel:
    attributes:
      [CLASS_NAME]:
        [FIELD_NAME]: ''

它不会显示在错误上。