1

I have a simple Model - Shop in my Ruby/MongoMapper application.

I have no idea why sometimes I only get one error message, and sometimes I get three error messages like this one:

'Validation failed: User has already been taken, User has already been taken, User has already been taken'

Yes, I am adding the same user_id multiple times, on purpose.

Here is my code:

class Shop
  include MongoMapper::Document
  key :user_id, String, :required => true, :unique => true

  def self.add
    begin
      ut = Shop.new
      ut.user_id = '11'
      ut.save!
      ut = nil
    rescue Exception => e
      puts e.message
    end
  end
end

Result:

# 'Validation failed: User has already been taken, User has already been taken, User has already been taken'

UPDATE:

Seems like removing the

ut = nil

fixes the 'problem'. But why...

7
  • What happens if you use AR-style validates_presence_of :user_id and validates_uniqueness_of :user_id` validations? Commented Nov 25, 2013 at 0:31
  • MongoMapper has some, um, quirks so I'm wondering if a different approach works better. Looks like it is going through the validation several times. Commented Nov 25, 2013 at 17:25
  • When I run code once - works fine. But on the second run, it fails until I run the script again (stop/ start) Commented Nov 25, 2013 at 20:36
  • You could try to add your own validates :some_method with a few logging calls in some_method to take a quick look at what MongoMapper is doing. Commented Nov 26, 2013 at 0:20
  • ok thanks I will. but so far this happens randomly... Commented Nov 26, 2013 at 11:32

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.