Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Mongoid Validation for create! - how to display error messages

I'm using Rails 3 with mongoid 2 and have a simple question regarding mongoid validation.

if @forum.topics.create!(name: params[:topic][:name])
   # success, do something
else
  #should handle errors but doesn't
    render 'new'
end

If I use the .create! method, it runs validations on a mongoid model class correctly, but it is not getting to the else block to display the error. Instead it returns a rails error page saying...

Mongoid::Errors::Validations in TopicsController#create

Validation failed - Name can't be blank.

That's good, but how do I display that in a view instead of getting an ugly rails error message page?

like image 931
HelloWorld Avatar asked Nov 15 '12 19:11

HelloWorld


1 Answers

Try this way:

new_topic = @forum.topics.new(name: params[:topic][:name])
if new_topic.save
   # success, do something
else
  render 'new', errors: new_topic.errors.full_messages
end

with this way you will have the local variable errors which is a Hash formated like following:

new_topic.errors.full_messages # => ["\"Name\" can't be blank"]
like image 171
MrYoshiji Avatar answered Oct 04 '22 23:10

MrYoshiji