Search code examples
ruby-on-railsruby-on-rails-3mongodbmongoid

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?


Solution

  • 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"]