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

后端 未结 9 1344
醉梦人生
醉梦人生 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: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!

提交回复
热议问题