Make semantic_errors render the exact error-message

爱⌒轻易说出口 提交于 2019-12-10 15:18:14

问题


I have a model Camping which has_many Images. At least one image is required on Camping:

class Camping < ActiveRecord::Base
  attr_accessible :images_attributes
  has_many :images
  validates_presence_of :images, :message => "At least one image is required"
  accepts_nested_attributes_for :images, :allow_destroy => true
 end

Then, in active_admin, which uses formtastic, I render the error message At least one image is required, with f.semantic_errors:

ActiveAdmin.register Camping do
  form :html => { :multipart => true } do |f|
     f.semantic_errors :images
     #....
     f.inputs "Images" do
      f.has_many :images do |img|
        #....
      end
    end
    #....
  end
end

This renders as:

Images At least one image is required.

How can I make it render: At least one image is required?

changing the f.semantic_errors :images into 'f.semantic_errors (removing :images) makes it render nothing; no error at all.

Note: The API documentation seems to imply that Formtastic always adds the :attribute name to the error; but I am not entirely sure how this code works.


回答1:


If you want to use such custom messages you can add error messages that are related to the object’s state as a whole, instead of being related to a specific attribute

Change this

validates_presence_of :images, :message => "At least one image is required"

to something like

   validate :should_have_images
   def should_have_images
       errors.add(:base, "At least one image is required") if images.blank?
   end



回答2:


If you want to use such custom messages you can add new method to Formtastic::Helpers::ErrorsHelper As follows

create new file at config/initializers/errors_helper.rb

Place following code to file

module Formtastic
  module Helpers
    module ErrorsHelper
      def custom_errors(*args)
        return nil if @object.errors.blank?
        messages = @object.errors.messages.values.flatten.reject(&:blank?)
        html_options = args.extract_options!
        html_options[:class] ||= 'errors'
        template.content_tag(:ul, html_options) do
          messages.map do |message|
            template.content_tag(:li, message)
          end.join.html_safe
        end
      end
    end
  end
end

In activeadmin form use f.custom_errors instead of f.semantic_errors *f.object.errors.keys



来源:https://stackoverflow.com/questions/14443140/make-semantic-errors-render-the-exact-error-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!