使语义错误呈现准确的错误消息 [英] Make semantic_errors render the exact error-message

查看:306
本文介绍了使语义错误呈现准确的错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型 Camping ,其中 has_many 图片 。露营时至少需要一张图片:

  class Camping< ActiveRecord :: Base 
attr_accessible:images_attributes
has_many:images
validates_presence_of:images,:message => 至少需要一张图片
accepts_nested_attributes_for:images,:allow_destroy => true
end

然后,在似乎暗示Formtastic总是在错误中添加:attribute 名称;但是我不太确定这段代码是如何工作的。

解决方案

如果您要使用此类自定义消息,则可以添加以下错误消息:与对象的整体状态有关,而不与特定属性有关



更改此

  validates_presence_of:images,:message => 至少需要一张图片 

类似

 验证:should_have_images 
def should_have_images
errors.add(:base,至少需要一张图像)如果images.blank?
结束


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.

解决方案

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

这篇关于使语义错误呈现准确的错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆