Skip to content

Instantly share code, notes, and snippets.

@matatabi
Created October 18, 2010 14:41
Show Gist options
  • Save matatabi/632317 to your computer and use it in GitHub Desktop.
Save matatabi/632317 to your computer and use it in GitHub Desktop.
nested_attributes を使った際にエラーメッセージを正しく表示させる
# config/initializers/errors_i18n.rb
ActiveModel::Errors.module_eval do
def full_messages
full_messages = []
each do |attribute, messages|
messages = Array.wrap(messages)
next if messages.empty?
if attribute == :base
messages.each {|m| full_messages << m }
else
# attr_name = attribute.to_s.gsub('.', '_').humanize
attr_name = convert_name(attribute.to_s)
attr_name ||= attribute.to_s.gsub('.', '_').humanize
attr_name = @base.class.human_attribute_name(attribute, :default => attr_name)
options = { :default => "%{attribute} %{message}", :attribute => attr_name }
messages.each do |m|
full_messages << I18n.t(:"errors.format", options.merge(:message => m))
end
end
end
full_messages
end
def to_text
output_string = ""
full_messages.each{|attr,msg| output_string << "#{attr} - #{msg}\n" }
output_string
end
def convert_name(name)
default = nil
if name =~ /(.+)\.(.+)/
base_name = $1
attribute = $2
# base = ActiveSupport::Dependencies.constantize(base_name.camelize)
base = ActiveSupport::Dependencies.constantize(base_name.camelize.singularize)
if (base.respond_to? :model_name)
default = "#{base.model_name.human} #{base.human_attribute_name(attribute.to_sym, :default => attribute.humanize)}"
end
end
default
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment