views:

1331

answers:

2

Hi, I need to display error message on model in rails,

my coding on model is like this,

if my_address.valid?
  # I need here the validation error.
   return nil
end

I used errors.add("Invalid address") but it is not working

please help to solve this problem ,

+1  A: 

I suggest taking a look at how scaffolds (script/generate scaffold my_model) displays validation errors.

Here's a short summary:

def create
  @post = Post.new(params[:post])

  if @post.save # .save checks .valid?
    # Do stuff on successful save
  else
    render :action => "new"
  end
end

In the "new" view, you'll use @post.errors, most likely with <%= error_messages_for :post %>.

August Lilleaas
+2  A: 

You will be able to access the errors via object.errors, i.e. for your case my_address.errors. It will return Error objects, you can check up on it here: http://api.rubyonrails.org/classes/ActiveRecord/Errors.html

Staelen
To further clarify, you can access the errors for a given attribute with `object.errors.on(:attr)' which will return the error message(s)
Tate Johnson