Gregory Worrall
Gregory Worrall

Reputation: 181

Running a daily script affecting the database

I want to write a script that I can configure a cron to run every 24 hours beneath my Rails app.

script.rb

User.all.each do |user|
    days = user[:days]

    if days >= 1
        days = days - 1
    end

    user.update_attribute(:days, days)
end

However, whenever I run this, I get this error:

uninitialized constant User (NameError)

What's going wrong?

Upvotes: 1

Views: 96

Answers (3)

Aetherus
Aetherus

Reputation: 8898

I always use whenever to manage my cron jobs.

Install whenever, then add the following script to your config/schedule.rb:

every :day do
  runner 'User.all.each {|user| user.decrement!(:days) if user.days > 0}'
end

Then run whenever -w from your terminal.

Upvotes: 0

dimakura
dimakura

Reputation: 7655

If you are in Rails app's home directory, then simply:

rails runner -e production script.rb

For cron (suppose, script.rb is in home dir again):

  1. Find out full path to your bundle (which bundle)
  2. In your crontab add (change bundle and project paths accordingly):

    0 * * * * cd /project_home && /bundle_executable exec rails runner -e production script.rb

Upvotes: 2

Chris Meyer
Chris Meyer

Reputation: 1621

Another approach is to require_relative 'config/environment.rb' (adjust paths to your use case) at the top of the script; There's a slight performance hit, but if you are only running this once a day, a few seconds of startup penalty won't matter.

Also, you may need to set RAILS_ENV appropriately to access the proper database tables.

Upvotes: 0

Related Questions