【问题标题】:validating fields, validating associated models, and the order or error messages验证字段、验证关联模型以及订单或错误消息
【发布时间】:2010-02-04 02:55:44
【问题描述】:

我有几个关于验证的问题,我不知道该怎么做。任何帮助表示赞赏。

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

我有 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

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

谢谢

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      这可能无法完全回答您的帖子,但是当您想要一个非常具体的验证例程时,简单地覆盖验证函数通常很方便。

      例如,如果您知道他们将密码长度完全留空,这使您不必费心检查密码长度的有效性,这样他们就不会收到消息说他们将密码长度留空并且密​​码长度不是 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
      

      【讨论】:

      • 我在想我做错了什么,但你有一些好的观点。谢谢。
      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2011-11-15
        • 1970-01-01
        • 2019-04-28
        • 2021-06-13
        • 2018-12-09
        • 1970-01-01
        • 2012-06-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多