How do I run Ruby tasks that use my Rails models?

后端 未结 9 1310
醉梦人生
醉梦人生 2021-02-01 08:58

I have a Rails app with some basic models. The website displays data retrieved from other sources. So I need to write a Ruby script that creates new instances in my database. I

相关标签:
9条回答
  • 2021-02-01 09:24

    I agree with the answer above but you have to include => :environment in your task or it will not load the Rails environment.

    e.g.,

    namespace :send do
      namespace :trial do
        namespace :expiry do
          desc "Sends out emails to people who's accounts are about to expire"
          task :warnings => :environment do
            User.trial_about_to_expire.has_not_been_notified_of_trial_expiry.each do |user|
              UserMailer.deliver_trial_expiring_warning(user)
              user.notified_of_trial_expiry = true
              user.save
            end
          end
        end
      end
    end
    
    0 讨论(0)
  • 2021-02-01 09:25

    Easiest way to run ruby tasks that interact with rails app/models is to make Rails generate Rake tasks for you!! :)

    Here's an example

    1. run rails g task my_namespace my_task

    2. This will generate a file called lib/tasks/my_namespace.rake which looks like:

    namespace :my_namespace do
    desc "TODO: Describe your task here"
      task :my_task1 => :environment do
        #write any ruby code here and also work with your models
        puts User.find(1).name
      end
    end
    
    1. Run this task with rake my_namespace:my_task

    2. Watch your ruby code task that interacts with rails modal run!

    0 讨论(0)
  • 2021-02-01 09:27

    I wrote up a post about this a while back.

    http://www.rawblock.com/2007/06/14/ruby-oracle-mac-os-x-pain-jruby-and-activerecord-jdbc-to-the-rescue/

    0 讨论(0)
提交回复
热议问题