rails错误消息显示键,我只想要值
我有以下代码来显示错误消息:
以下是模型中的validation:
validates :title, presence: true, length: {maximum: 50, minimum: 5, too_long: "Title cannot be longer than %{count} characters", too_short:" must be at least %{count} characters."}
出于某种原因,这会打印带有错误的属性名称和错误。 例如,如果我试图通过更新名为“title”的表单字段来显示错误,则错误消息将显示为:
Title Title cannot be longer than 50 characters
我想在整个网站上显示许多错误消息,我不想自动编写任何内容。 我如何在开头摆脱“标题”这个词?
full_messages
方法将attribute name
到validation error message
。 以下是rails
的方法实现
## Following code is extracted from Rails source code def full_messages map { |attribute, message| full_message(attribute, message) } end 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
如果你看到full_messages
方法,它又调用full_messages
其中属性被添加到错误消息的前面。 因此,如果您在validation error message
添加attribute name
,那么它肯定会重复,这就是您的情况。
简而言之,您不需要在validation消息中指定属性名称,因为rails已经在处理它。
编辑
没有什么是不可能的。 如果您需要,您可以自定义如下
<% if @profile.errors.any? %> <% @profile.errors.messages.each do |attr, msg| %> <% msg.each do |val| %> - <%= val %>
<% end %> <% end %>
<% end %>
我会使用这样的message
。 我认为这解决了你的问题。
validates :title, presence: true, length: { maximum: 50, minimum: 5, message: 'Title should be between 5 and 50 characters' }
然后在视图中
<% @profile.errors.each do |attr, msg| %> <% puts 'errors ared' + msg.to_s %> <%= msg %> <% end %>
关键是使用errors
而不是full_messages
,然后在attr
和msg
拆分每个错误,只获得message
或撰写消息。
- 如何在erb模板中发表评论?
- Rails 3.1.0中出现“Encoding :: InvalidByteSequenceError”错误
- 如何在Ruby中将字符串转换为字节?
- 自定义错误页面 – Ruby on Rails
- 如何使用RubyGem Sanitize变换器将无序列表清理为逗号分隔列表?
- / usr / bin / env ruby没有这样的文件或目录:使用capistrano 3,capistrano / rbenv,capistrano / bundler和capistrano / rails(使用rails 4)
- VPS apache config – 添加最新的乘客gem后,命令’PassengerDefaultRuby’无效
- 如何在activerecord之外创建activerecord样式validation?
- 让Rails 2.3.x忽略i18n gem