How to not have Mongoid 4 validate foreign key association on new/create/update_attributes?

73 views
Skip to first unread message

Jon

unread,
Apr 4, 2015, 7:49:46 AM4/4/15
to mon...@googlegroups.com
Hey all, I'm seeing some unexpected behavior where Mongoid is validating a foreign key relationship if I new/create an object. I don't want this, as we create millions of documents each day and not everything is sharded on _id so it causes inefficient scatter-gather queries. Here's an example:

```
class Test1
  include Mongoid::Document
  belongs_to :test2
end

class Test2
  include Mongoid::Document
  has_many :test1s
end

Moped.logger = Logger.new(STDOUT)

# This will cause a database call to check for the Test2 object, and when it finds none, it'll set the test2_id field to nil.
t = Test1.new(:test2_id => BSON::ObjectId.new)

D, [2015-04-04T07:42:56.517018 #88944] DEBUG -- :   MOPED: 127.0.0.1:27017 QUERY        database=development collection=test2s selector={"$query"=>{"_id"=>BSON::ObjectId('551fce406a6f6e5b70000000')}, "$orderby"=>{:_id=>1}} flags=[] limit=-1 skip=0 batch_size=nil fields=nil runtime: 0.6270ms
 => #<Test1 _id: 551fce406a6f6e5b70010000, test2_id: nil>

# However, setting the relationship after the new doesn't cause any extra queries to get made
t.test2_id = BSON::ObjectId.new
 => BSON::ObjectId('551fce566a6f6e5b70060000')

# But doing it with update_attributes does, returns true but doesn't do the update anyway
new_id = BSON::ObjectId.new
2.1.5 :028 > t.update_attributes(:test2_id => new_id)
D, [2015-04-04T07:47:33.777148 #88944] DEBUG -- :   MOPED: 127.0.0.1:27017 QUERY        database=development collection=test2s selector={"$query"=>{"_id"=>BSON::ObjectId('551fcf526a6f6e5b70090000')}, "$orderby"=>{:_id=>1}} flags=[] limit=-1 skip=0 batch_size=nil fields=nil runtime: 0.7210ms
 => true
2.1.5 :029 > t.test2_id == new_id
 => false
```

If I add `Mongoid::Attributes::Dynamic` to Test1, then this behavior also goes away. I've tried adding `:validate => false` to each relation but that doesn't help (I wouldn't have expected it to since this behavior is on new/create, not on save).

Jon

unread,
Apr 4, 2015, 7:50:21 AM4/4/15
to mon...@googlegroups.com
I should say I'm in the process of upgrading to Mongoid 4.0.2, Rails 4.2.0 from Mongoid 3.1.5.

Jon

unread,
Apr 5, 2015, 7:35:30 AM4/5/15
to mon...@googlegroups.com
Turns out that I caused this regression with a pull, so it only is affecting master. https://github.com/mongoid/mongoid/pull/4025 should fix it.


On Saturday, April 4, 2015 at 7:49:46 AM UTC-4, Jon wrote:
Reply all
Reply to author
Forward
0 new messages