【问题标题】:Rails full error message without attribute没有属性的 Rails 完整错误消息
【发布时间】:2019-11-27 15:06:17
【问题描述】:

我无法摆脱错误消息中的属性。 (我想知道为什么这不是默认行为)

控制器

if @item.save
      ...
 else
   format.html { redirect_to [@profile, :items], alert: @item.errors.full_messages}
end

it.yml

 it:
  errors:
    format: "%{message}"

View.html

<% if alert %>
    <% Array.wrap(alert).each do |msg| %>
        <%=msg%>
    <% end %>
<% end %>

但我得到了这个输出

属性名称我的自定义消息

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-6


    【解决方案1】:

    使用messages 代替full_messages

    @item.errors.messages.values.flatten
    

    由于messages 返回一个哈希,其中的键显示验证错误是什么,您可以简单地获取并展平所有值。

    { :email=>["Another record exists with this email."], ... } # for example
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多