Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails/Mongoid error messages in nested attributes

I have a contact info class defined like this:

class ContactInfo
  include Mongoid::Document

  validates_presence_of :name, :message => ' cannot be blank'

  field :name, :type => String
  field :address, :type => String
  field :city, :type => String
  field :state, :type => String
  field :zip, :type => String
  field :country, :type => String
  embedded_in :user
end

This contact info class is embedd as a nested attribute inside my user class:

class PortalUser
  include Mongoid::Document
  accepts_nested_attributes_for :contact_info
end

When I attempt to save a user without a name, I get an error message like this:

Contact info is invalid

However, this is not very useful to the end user, because he or she doesn't know what contact info is invalid. The REAL message should be 'Name cannot be blank'. However, this error is not being propagated upwards. Is there a way to get the 'Name cannot be blank' message inside the user.errors instead of the 'Contact info is invalid' error message?

Thanks

like image 290
Richard Avatar asked Mar 31 '11 14:03

Richard


2 Answers

Here's the solution I eventually came up with:

Added these lines to the user class

after_validation :handle_post_validation
def handle_post_validation
  if not self.errors[:contact_info].nil?
    self.contact_info.errors.each{ |attr,msg| self.errors.add(attr, msg)}
    self.errors.delete(:contact_info)
  end
end
like image 116
Richard Avatar answered Oct 03 '22 03:10

Richard


Instead of returning the user.errors.full_messages create a specific error message method for your user model where you handle all your embedded document errors.

class PortalUser
  include Mongoid::Document
  accepts_nested_attributes_for :contact_info
  def associated_errors
    contact_info.errors.full_messages unless contact_infos.errors.empty?
  end
end

and in your controller

flash[:error] = user.associated_errors
like image 22
Alexis Perrier Avatar answered Oct 03 '22 04:10

Alexis Perrier