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 namevalidation 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 ,然后在attrmsg拆分每个错误,只获得message或撰写消息。