Skip to content

Commit

Permalink
Mongoize is not called on update_all, when $set operator is used (#5815)
Browse files Browse the repository at this point in the history
* update tests to highlight a problem with mongoize in $set operation

* fix params in mongoize_for method call

* align with the mongoize_for method annotation

* fix failing test
  • Loading branch information
dem committed May 13, 2024
1 parent dce18b8 commit 2281f0d
Show file tree
Hide file tree
Showing 4 changed files with 12 additions and 5 deletions.
4 changes: 2 additions & 2 deletions lib/mongoid/extensions/hash.rb
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ def __consolidate__(klass)
consolidated[key].update(value)
else
consolidated["$set"] ||= {}
consolidated["$set"].update(key => mongoize_for(key, klass, key, value))
consolidated["$set"].update(key => mongoize_for("$set", klass, key, value))
end
end
consolidated
Expand Down Expand Up @@ -199,7 +199,7 @@ def value_for(operator, klass, key, value)
case operator
when "$rename" then value.to_s
when "$addToSet", "$push" then value.mongoize
else mongoize_for(operator, klass, operator, value)
else mongoize_for(operator, klass, key, value)
end
end

Expand Down
6 changes: 3 additions & 3 deletions spec/mongoid/contextual/mongo_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3765,15 +3765,15 @@
context "when the attributes must be mongoized" do

before do
context.update_all("$set" => { member_count: "1" })
context.update_all("$set" => { location: LatLng.new(52.30, 13.25) })
end

it "updates the first matching document" do
expect(depeche_mode.reload.member_count).to eq(1)
expect(depeche_mode.reload.location).to eq(LatLng.new(52.30, 13.25))
end

it "updates the last matching document" do
expect(new_order.reload.member_count).to eq(1)
expect(new_order.reload.location).to eq(LatLng.new(52.30, 13.25))
end
end
end
Expand Down
1 change: 1 addition & 0 deletions spec/support/models/band.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ class Band
field :mojo, type: Object
field :tags, type: Hash
field :fans
field :location, type: LatLng

embeds_many :records, cascade_callbacks: true
embeds_many :notes, as: :noteable, cascade_callbacks: true, validate: false
Expand Down
6 changes: 6 additions & 0 deletions spec/support/models/lat_lng.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ class LatLng
attr_accessor :lat, :lng

def self.demongoize(object)
return if object.nil?

LatLng.new(object[1], object[0])
end

Expand All @@ -14,4 +16,8 @@ def initialize(lat, lng)
def mongoize
[ lng, lat ]
end

def ==(other)
lat == other.lat && lng == other.lng
end
end

0 comments on commit 2281f0d

Please sign in to comment.