Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

accessing rails models from rake task

How can I access model objects from rails rake task?

If I initialize my rufus scheduler $scheduler = Rufus::Scheduler.start_new in my rake would that scheduler stay alive since it's from a rake task?

like image 705
ed1t Avatar asked Dec 27 '22 18:12

ed1t


1 Answers

To access a rails model in your rake task you need to load the :environment.

task :my_task => [:environment] do
  User.new #...
end

You would not call the scheduler within a task but the other way around. You need to start a Rufus scheduler and then call your rake tasks from them.

You need to first

# other require statements ...
require 'rake'

# ...

scheduler = Rufus::Scheduler.start_new
scheduler.cron "00 6 * * *" do
  Rake::Task["sometask"].invoke
end
like image 171
ayckoster Avatar answered Jan 09 '23 11:01

ayckoster