Rails 5 Simple Form不显示错误

Rails 5 Simple Form does not display errors

让我的简单表单显示错误的唯一方法是通过

  <% errors = f.object.errors.messages.collect { |k,v| "#{k}: #{v}" if v.length > 0 }.join("\n")%>
  <%= f.error_notification message: "Errors: #{errors}" %>

这似乎太复杂了。

场景:

用户 table 和 social_profile 链接(facebook、twitter 等)的嵌套、多态 table。

如果用户在创建新帐户时未填写任何嵌套表单,则配置文件 inputs/params 为空字符串并且可以正常保存。

但是,如果用户删除所有配置文件链接的输入字段,则不会创建与 social_profile table 的关联。因此,如果用户稍后尝试编辑他的帐户,嵌套的 social_profile 表单将不会显示。

validates :social_profile, presence: true, associated: true 添加到用户模型可防止此错误发生,但没有向用户说明发生了什么。我能想到的最好的是原始代码,但似乎应该有更好的方法。

@Brad Werth 将我链接到 this SO post 这帮助我构建了以下答案:

<%= f.object.errors.full_messages.join(", ") if f.object.errors.any? %>

从表单中获取错误的对象,获取 "full_messages"(即 "Description cannot be blank")并用逗号将它们连接在一起。