Reputation: 7451
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 ,
Upvotes: 1
Views: 11203
Reputation: 7841
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
Upvotes: 3
Reputation: 54593
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 %>
.
Upvotes: 2