mongoid/mongoid — Issue #1541: find_or_create_by not working?
Author: behrangsa
Created: 2012-01-01 05:01:42+00:00
State: open

*Mongoid 2.3.4*
*MongoDB 2.0.1*

I have a `Counter` document defined as:

```ruby
class Counter
include Mongoid::Document

field :collection_name, type: String
field :count, type: Integer, :default => 1

validates_presence_of :collection_name
validates_presence_of :count

def self.next(collection_name)
counter = Counter.find_or_create_by(:collection_name => collection_name)
counter.update({
'$inc' => { 'count' => 1}
})
counter.count
end
end
```

In Rails console, when I run `find_or_create_by(:collection_name => 'MyCollection')`, the returned `Counter`'s `:collection_name ` remains `nil`:

```ruby
Counter.find_or_create_by(:collection_name => "MyCollection")
=> #
```

In the DB, the documented is persisted as:

```json
{ "_id" : ObjectId("4effe84d1d9ba710b4000006"), "count" : 1 }
```

Seems to me that the validation should also have failed.

Is this a bug or am I doing something wrong?