我有以下验证:
validates_presence_of :price, :message => "my message"
当价格为空时我收到以下错误:
为我的消息定价
是否有办法不在邮件中包含列名(price
)?
我试着这样做:
validates_presence_of :price, :message => "^ my message"
建议here,但它对我不起作用。我收到以下消息:
价格^我的消息
答案 0 :(得分:3)
^技术在Rails 3中的dynamic_form gem中定义。将其添加到Gemfile中,运行bundle update
,它应该可以工作。这也让你只需把<%= f.error_messages%>在您的表单中,以避免格式化消息的大量额外工作。
答案 1 :(得分:1)
我认为最好和最灵活的方法是为表单字段编写自己的帮助器。显示用户输入错误因应用程序和布局到布局而异。
# lib/required_attributes.rb
module ActiveModel
module Validations
module ClassMethods
# ruby-1.9.2-head > Product.required_attributes
# => [:publisher_symbol_code, :price]
def required_attributes
presence_validators = self.validators.find_all {|v| v.class == ActiveModel::Validations::PresenceValidator }
presence_validators.map(&:attributes).flatten
end
end
end
end
# application_helper.rb:
def mark_as_required
content_tag :span, '*', :class => :required
end
def form_field_for(object, *args, &block)
options = args.extract_options!
attributes = args.map(&:to_sym)
field_contents = capture(&block)
classes = "form-field clear #{options[:class]}"
if options[:hint]
field_contents << content_tag(:p, options[:hint], :class => :inline_hint)
end
# Are there any required attributes?
any_attribute_required = (object.class.required_attributes & attributes).present?
if options[:label]
object_name = object.class.to_s.underscore # 'product'
label_contents = "#{options[:label]}: #{mark_as_required if any_attribute_required}".html_safe
label_html = label(object_name, attributes.first, label_contents, :class => 'form-label fl-space2')
field_contents = label_html + field_contents
end
errors = attributes.inject([]) do |mem, attrib|
mem << object.errors[attrib]
mem
end.flatten.compact.uniq
if errors.present?
classes << ' error'
field_contents << content_tag(:p, errors.join(', '), :class => :inline_errors)
end
content_tag(:div, field_contents, :class => classes)
end
然后在视图中:
= form_field_for @product, :publisher_symbol, :label => "Symbol", :hint => "pick a product symbol" do
= product_form.text_field :publisher_symbol, :size => 70
如果有一组输入可能会对任何字段发生错误,您可以按如下方式对它们进行分组:
= form_field_for @product, :publication_year, :publication_month, :publication_day, :label => "Publication date" do
= product_form.text_field :publication_year, :class => 'text fl', :size => 5
= product_form.text_field :publication_month, :class => 'text fl', :size => 5
= product_form.text_field :publication_day, :class => 'text fl', :size => 5
发生错误时,您的视图如下所示:
<div class="form-field clear error">
<div class="field_with_errors">
<label class="form-label fl-space2" for="product_publisher_symbol">Symbol: <span class="required">*</span></label>
</div>
<div class="field_with_errors">
<input class="text fl" id="product_publisher_symbol" name="product[publisher_symbol]" size="70" type="text" value="">
</div>
<p class="inline_hint">pick a product symbol</p>
<p class="inline_errors">can't be blank</p>
</div>
这段代码需要一些重构,但你明白了。如果你比我更懒,并且不想在所有视图中输入'form_field_for',那么创建一个自定义表单构建器:)