我有以下型号:
class Group
...
has_many :users, dependent: :delete
...
end
class User
belongs_to :group
has_one :invitation, dependent: :destroy, foreign_key: 'to_id'
validates_presence_of :group
end
class Invitation
belongs_to :to, class_name: "User"
validates :to, presence: true
end
如果我创建一个新group = Group.create!(name: 'foo')
的,group.persisted? => true
然后更新一个用户的组user.update_attributes!(group: group)
:
MONGODB (1.4ms) db['system.namespaces'].find({})
MONGODB (13.7ms) db['invitations'].find({"to_id"=>BSON::ObjectId('5170657d627b165f33000002')}).limit(-1).sort([[:_id, :asc]])
MONGODB (204.4ms) db['users'].find({:deleted_at=>nil, "user_id"=>BSON::ObjectId('5170657d627b165f33000002')}).limit(-1).sort([[:_id, :asc]])
MONGODB (1.0ms) db['groups'].find({:deleted_at=>nil, :_id=>BSON::ObjectId('516db306627b164bdb000012'), :_type=>{"$in"=>["Account"]}}).limit(-1).sort([[:_id, :asc]])
MONGODB (183.2ms) db['$cmd'].find({"count"=>"users", "query"=>{:deleted_at=>nil, :slug=>"7d3a-jonathan-grin", :_id=>{"$ne"=>BSON::ObjectId('5170657d627b165f33000002')}}, "fields"=>nil}).limit(-1)
MONGODB (0.2ms) db['users'].update({"_id"=>BSON::ObjectId('5170657d627b165f33000002')}, {"$set"=>{"slug"=>"7d3a-jonathan-grin", "updated_at"=>2013-05-02 20:54:42 UTC}})
=> true
正如您在 Mongoid log ( update
method) 的最后一句中看到的,未设置组。
如果我user.update_attributes!(group: group)
再次运行:
MONGODB (132.9ms) db['$cmd'].find({"count"=>"users", "query"=>{:deleted_at=>nil, :slug=>"1e30-jonathan-grin", :_id=>{"$ne"=>BSON::ObjectId('5170657d627b165f33000002')}}, "fields"=>nil}).limit(-1)
MONGODB (0.1ms) db['users'].update({"_id"=>BSON::ObjectId('5170657d627b165f33000002')}, {"$set"=>{"group_id"=>BSON::ObjectId('5182d256218c5a0c8a000004'), "slug"=>"1e30-jonathan-grin", "updated_at"=>2013-05-02 20:56:34 UTC}})
=> true
我只收到两个查询,并且该组已更新。
同样发生在group.users << user
.
- 所有回调都已注释。
- 我正在 Rails 控制台中对其进行测试。
- MongoDB 2.2.3 版
- Mongoid 版本 2.6.0
谢谢!