Running Rake tasks

0

An example of a rake task that skips updating the updated_at column. To run this rake task type:

rake maintenance:move_topics RAILS_ENV=production

/lib/tasks/maintenance.rake
namespace :maintenance do

  # usage: rake maintenance:move_topics RAILS_ENV=production
  desc "change topics to different groups"
  task move_topics: :environment do    
    ActiveRecord::Base.record_timestamps = false #skips updating updated_at
    gto    = Group.find 11
    gfrom  = Group.find 10
    [21, 22, 23].each do |id|
      topic = Topic.find id
      # topic.update!(group: g10)
      topic.update!(group_id: gto.id)
    end
    # Group.reset_counters(gto.id,   :topics)
    # Group.reset_counters(gfrom.id, :topics)
  end

end

For some reason Rails 5.2.1 increments (and decrements) counter cache counters twice so I ended up doing topic.update!(group_id: g10.id) instead of topic.update!(group: g10) and Group.reset_counters(g10.id, :topics); Group.reset_counters(g6.id, :topics)

References
1. https://guides.rubyonrails.org/command_line.html#custom-rake-tasks

  • 0 posts
  • 0 subtopics
  • 10 days ago by vince