【问题标题】:Rails - Monkey-patch rails full_messagesRails - Monkey-patch rails full_messages
【发布时间】:2016-07-07 01:37:42
【问题描述】:

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

我发现了一个猴子修补完整消息的网站,因此您可以在不显示属性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

有什么想法吗?

【问题讨论】:

  • 为什么要猴子补丁呢?为什么不创建自己的帮助器来显示错误?
  • 我有一些表单,其中有一些我希望显示属性的字段和一些我不希望显示的字段。
  • 这并不能回答问题,您不认为创建自己的方法而不是在 Rails 方法上进行猴子补丁并冒险在每次更新时破坏它会更好吗?
  • 是的,我确实认为这会更好,但我不认为可以有选择地选择何时显示属性。

标签: ruby-on-rails activerecord monkeypatching


【解决方案1】:

您还可以将字段翻译为空字符串。 Rails 会在

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

而且它不会显示在错误中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-30
    • 2013-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多