首页 > 解决方案 > ActiveRecord 任务在错误的环境中执行,无论何时

问题描述

我必须在我的 ActiveRecord 数据库中运行涉及一些数据清理的 Cron 任务。我正在使用每当宝石。这是代码:

日程安排.rb

every 1.hour do
  rake 'notifications:clear'
end

通知.rake

namespace :notifications do
  task clear: :environment do
    Rpush::Notification.delete_all
  end
end

运行它会给我以下错误:

rake aborted!
ActiveRecord::NoDatabaseError: FATAL:  role "user_prod" does not exist

我在开发环境中。这是我的 database.yml 文件:

default: &default
  adapter: postgresql
  encoding: unicode
  # For details on connection pooling, see Rails configuration guide
  # http://guides.rubyonrails.org/configuring.html#database-pooling
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

development:
  <<: *default
  database: development_database

test:
  <<: *default
  database: test_database

staging:
  <<: *default
  database: staging_database
  username: user_staging
  password: <%= ENV['DATABASE_PASSWORD'] %>


production:
  <<: *default
  database: production_database
  username: user_prod
  password: <%= ENV['DATABASE_PASSWORD'] %>

关于为什么我的 ActiveRecord 指令似乎连接到我的生产环境的任何想法?提前致谢 !

标签: ruby-on-railsactiverecordwhenever

解决方案


使用以下更新您的代码:-

schedule.rb文件中:-

every 1.hour do
  rake 'notifications:clear', :environment => "development"
end

最后执行了这个命令:-

whenever --update-crontab

或者

清除现有的 cron 作业。

crontab -r

使用环境更新 cronjob。

whenever --update-crontab --set environment='development'

推荐阅读