验证字段,验证关联模型以及订单或错误消息

时间:2010-02-04 02:55:45

标签: ruby-on-rails

我对验证有几个问题,我无法弄清楚该怎么做。任何帮助表示赞赏。

在页面上显示错误消息时,我无法控制错误消息的顺序。

我有validates_associated属性,它确实验证了各个字段,但它还添加了一行“模型名称无效”。我不想要该错误消息,因为它已经显示了所有正确的错误消息。

class Recipe < ActiveRecord::Base
  has_many :recipe_steps
  has_many :recipe_ingredients

  validates_presence_of :title, :message => "cannot be left blank"
  validates_presence_of :servingsize, :message => "cannot be left blank"
  validates_presence_of :cookingtime, :message => "cannot be left blank"
  validates_numericality_of :cuisine_type_id, :greater_than => 0, :message => "Please select a cuisine type"
  validates_numericality_of :recipe_level_id, :greater_than => 0, :message => "Please select a recipe level"
  validates_associated :recipe_ingredients
  validates_associated :recipe_steps

  HUMAN_ATTRIBUTES = {
    :title => "Recipe title",
    :servingsize => "Serving size",
    :cookingtime => "Cooking time",
    :cuisine_type_id => "",
    :recipe_level_id => ""
  }

  def self.human_attribute_name(attr)
    HUMAN_ATTRIBUTES[attr.to_sym] || super
  end
end

如果你能分享一些很棒的链接,我找不到任何好的文档或教程。

由于

3 个答案:

答案 0 :(得分:2)

您应该使用Rails I18n配置自定义错误消息。

答案 1 :(得分:1)

这可能无法完全回答您的帖子,但是当您想要一个非常具体的验证例程时,通常只需覆盖验证功能即可。

这允许您例如在您知道密码长度完全为空的情况下不会检查密码长度的有效性,这样他们就不会收到一条消息,说明它们是空白的,并且它不是6个字符。长度。

示例:

def validate

  if self.thing.empty?
     errors.add_to_base "Please make sure you do this thing!" 
   end

   if self.other_thing.length < 4
     errors.add 'other_thing', 'must be 4 characters long minimum'
   else
      self.other_thing.include? 'naughty word'
        errors.add 'other_thing', 'can not include naughty words'
      end
   end
end

答案 2 :(得分:0)

我使用的是rails v2.3.4,其中错误集合没有使用有序列表。一旦我升级到2.3.5,错误集合就使用了有序列表,因此错误消息按照它们在模型中声明的顺序显示。