Make semantic_errors visualize the exact error message

I have a Camping model that has_many Images . Camping requires at least one image:

 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 get an error message. f.semantic_errors 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 is displayed as:

Example output of error

Images At least one image is required .

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

changing f.semantic_errors :images to ' f.semantic_errors (deletion: images) makes it display nothing; no mistake at all.

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

+4
source share
2 answers

If you want to use such custom messages, you can add error messages related to the state of objects in general, instead of being associated with a specific attribute

Change it

 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
source

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

create a new file in config/initializers/errors_helper.rb

Put the following code in a 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 mode, use f.custom_errors instead of f.semantic_errors *f.object.errors.keys

0
source

All Articles