Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoid Is it possible to override updated_at timestamp

I am trying to manually edit the "updated_at" field through a rake task

Here is what it looks like:

task :campaigns_updated_at_recovery => :environment do

Dir.foreach('db/raw-data/campaigns/') do |json|
  next if json == '.' or json == '..'
  file = File.read('db/raw-data/campaigns/'+json)
  data_hash = JSON.parse(file)
  #p data_hash["_id"]
  thisCampaign = Campaign.find(data_hash["_id"])
  thisCampaign["channels"].each do |chan|
    if chan["updated_at"] < Date.new(2018,04,19)
      data_hash["channels"].each do |channel|
        if chan["_id"].to_s == channel["_id"]
          chan["updated_at"] = Date.parse(channel["updated_at"])
        end
      end
    end
    thisCampaign.save
  end
end

However when I run this task, the updated_at date is either not changed or updated to today's date. What am I missing ?

I am using Mongoid and not ActiveRecord by the way

like image 917
RayedB Avatar asked Dec 20 '25 15:12

RayedB


1 Answers

updated_at is updated by mongoid itself in a callback.

You have two solution to work around that.

The easiest solution would be to use set to change the value directly without firing any callback:

thisCampaign.set(channels: thisCampaign['channels'])

The more flexible solution would be to go down to the driver level. The basic idea is:

Campaign.collection.find(_id: data_hash["_id"]).update_one({
  '$set' => {
    updated_at: yourDate
  }
})

Given your example, you would first need to get the full document

thisCampaign = Campaign.collection.find(_id: data_hash["_id"]).first
if thisCampaign
  thisCampaign["channels"].each do |chan|
    if chan["updated_at"] < Date.new(2018,04,19)
      data_hash["channels"].each do |channel|
        if chan["_id"].to_s == channel["_id"]
          chan["updated_at"] = Date.parse(channel["updated_at"])
        end
      end
    end
  end
  Campaign.collection.find(_id: data_hash["_id"]).update_one({
    '$set' => {channels: thisCampaign["channels"]}
  })
end
like image 180
Geoffroy Avatar answered Dec 22 '25 11:12

Geoffroy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!