首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails - Monkey-patch rails full_messages

Rails - Monkey-patch rails full_messages
EN

Stack Overflow用户
提问于 2016-03-20 23:46:17
回答 1查看 277关注 0票数 0

当我不将其设置为(Rails adding error to :base not working as expected)时,rails的错误消息会显示属性,这让我很不好受。

我发现了一个可以修补完整消息的站点,这样您就可以显示错误消息,而不会显示属性http://adamhooper.com/eng/articles/5

然而,这是相当旧的,rails从那时起就发生了变化。我想知道是否有可能在rails 4.2中制作相同的猴子补丁。

full_messages方法以前定义为:

代码语言:javascript
复制
...
    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

还有补丁:

代码语言:javascript
复制
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

当前的方法是:

代码语言:javascript
复制
# 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

有什么想法吗?

EN

回答 1

Stack Overflow用户

发布于 2018-10-18 23:23:09

您还可以将字段转换为具有空字符串。Rails将在

代码语言:javascript
复制
en:
  activemodel:
    attributes:
      [CLASS_NAME]:
        [FIELD_NAME]: ''

并且它不会显示在错误上。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36115893

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档