ruby on rails - Mongoid, calling update_attributes twice to persist change -
i have following models:
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
if create new group = group.create!(name: 'foo')
, group.persisted? => true
, update user's group 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
as can see in last sentence of mongoid log (update
method), group not being set.
if run user.update_attributes!(group: group)
once again:
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
i 2 queries , group updated.
same occurs group.users << user
.
- all callbacks commented.
- i'm testing in rails console.
- mongogodb version 2.2.3
- mongoid version 2.6.0
thanks!
which safety level using?
depending on how configure it, mongoid might reporting change persisted when in fact recorded in memory on mongodb server - not yet persisted disk
try this:
group.with(safe: {w:2,fsync:true}).create! # requires mongoid 3.x
or
group.safely(w:2, fsync: true).create! # requires mongoid 2.x
you can set default safety level in config/mongoid.yml
file of rails project.
see also:
http://mongoid.org/en/mongoid/docs/installation.html#configuration
http://two.mongoid.org/docs/persistence/safe_mode.html (mongoid 2.x)
the values can passed :safe are:
- true: persist in safe mode, no options.
- false: don't persist in safe mode.
- fsync: true|false: whether perform fsync.
- w: n: number of nodes write before returning.
- wtimeout: n: timeout value writing multiple nodes.
Comments
Post a Comment