Ruby on Rails:扩展ActiveRecord :: Errors

时间:2010-04-23 18:44:51

标签: ruby-on-rails activerecord

在Ruby on Rails中,将代码段中的代码放在http://gist.github.com/376389中的哪个位置?我想用可用的代码扩展ActiveRecord :: Errors,以便我可以合并错误消息。

这是针对ApplicationController的吗?还是为了lib?


从github.com粘贴

# monkey patch gleaned from http://dev.rubyonrails.org/attachment/ticket/11394/merge_bang_errors.patch
module ActiveRecord
  class Errors

    def merge!(errors, options={})
      fields_to_merge = if only=options[:only]
        only
      elsif except=options[:except]
        except = [except] unless except.is_a?(Array)
        except.map!(&:to_sym)
        errors.entries.map(&:first).select do |field|
          !except.include?(field.to_sym)
        end
      else
        errors.entries.map(&:first)
      end
      fields_to_merge = [fields_to_merge] unless fields_to_merge.is_a?(Array)
      fields_to_merge.map!(&:to_sym)

      errors.entries.each do |field, msg|
        add field, msg if fields_to_merge.include?(field.to_sym)
      end
    end
  end
end

2 个答案:

答案 0 :(得分:4)

您可以将其放入initializers目录中的任何ruby文件中(创建一个新文件,将其命名为您想要的任何名称)。 Rails每次启动时都会运行其中的所有文件,并在那时扩展Errors

答案 1 :(得分:0)

这个问题是陈旧的,但如果你想在rails 3.x中做类似的事情,可以将它放在config / initializers /目录下的文件中:

# monkey patch gleaned from http://dev.rubyonrails.org/attachment/ticket/11394/merge_bang_errors.patch

module ActiveModel
  class Errors
    def merge!(errors, options={})
      return if errors.blank? || errors.first.size < 2

      fields_to_merge = if only=options[:only]
        only
      elsif except=options[:except]
        except = [except] unless except.is_a?(Array)
        except.map!(&:to_sym)
        errors.entries.map(&:first).select do |field|
          !except.include?(field.to_sym)
        end
      else
        errors.entries.map(&:first)
      end
      fields_to_merge = [fields_to_merge] unless fields_to_merge.is_a?(Array)
      fields_to_merge.map!(&:to_sym)

      errors.entries.each do |field, msg|
        add field, msg if fields_to_merge.include?(field.to_sym)
      end
    end
  end
end