views:

84

answers:

3

Hi,

I have a couple of questions on validations and I cannot figure out what to do. Any help is appreciated.

I cannot seem to control the order of the error messages when they are display on the page.

I have validates_associated attribute and it does validate the individual fields but it also adds a line which says "model name is invalid". I don't want that error message since it already displays all the correct error messages.

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

I couldn't find any good documentation or tutorials, if you could share some links that would be great.

Thanks

+1  A: 

You should use Rails I18n to configure custom error messages.

Paul McMahon
okay, I will read up on it. Thanks
iHeartDucks
+1  A: 

This may not fully answer your post, but when you want to have a very specific validation routine, its often handy to simply override the validate function.

This allows you to for example not bother checking the validity of the password length if you know that they left it completely blank, so that they don't get a message that they left it blank and that it was not 6 characters in length.

example:

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
spotman
I was thinking that I was doing something wrong but you have some good points. Thanks.
iHeartDucks
A: 

I was using rails v2.3.4 in which the errors collection was not using an orderedlist. Once I upgraded to 2.3.5 the errors collection was using the orderedlist and hence the error messages are displayed in the order they were declared in the model.

iHeartDucks