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...

meso_2600
  • 1,940
  • 5
  • 25
  • 50
  • What happens if you use AR-style `validates_presence_of :user_id` and `validates_uniqueness_of `:user_id` validations? – mu is too short Nov 25 '13 at 00: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. – mu is too short Nov 25 '13 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) – meso_2600 Nov 25 '13 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. – mu is too short Nov 26 '13 at 00:20
  • ok thanks I will. but so far this happens randomly... – meso_2600 Nov 26 '13 at 11:32
  • I have edited main post: UPDATE: Seems like removing the ut = nil fixes the 'problem'. But why... – meso_2600 Nov 26 '13 at 15:11
  • I have checked mongodb logs and it seems like the command is being issued twice. But not always, sometimes it's issued after 10 requests and sometimes after second. But never the first... – meso_2600 Nov 26 '13 at 15:43

0 Answers0