form_for error messages in Ruby on Rails

前端 未结 4 866
离开以前
离开以前 2020-12-10 12:28

What is the preferred way to display validation error messages using form_for in Rails 4?

<%= form_for @post do |f| %>
  ...
<% end %&g         


        
4条回答
  •  猫巷女王i
    2020-12-10 13:03

    I know this isn't exactly what was asked, but if you are using the simple_form gem, which I recommend, you can use f.error_notification which takes :message as an option.

    = f.error_notification message: form_errors_for(your_object)
    

    I use a method pretty similar to Wes's answer; form_errors_for inside application_helper.rb

    def form_errors_for_base(object)
      if object.errors.messages[:base].present?
        object.errors.messages[:base].join(",\n") + "."
      else
        nil
      end
    end
    

提交回复
热议问题