Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby scripts with access to Rails Models

Where and how do I run a simple script that uses my rails environment. Specifically I have one column that holds multiple pieces of information, I've added columns now for each piece of information and need to run a ruby script that can run to call a method on each row of the database to extrapolate data and save it to the new column.

like image 762
Rabbott Avatar asked May 09 '11 20:05

Rabbott


3 Answers

Using a migration sounds like the right way to go if I am understanding your use case.

However, if you really do want to write a standalone script that needs access to your Rails application's models, you can require the environment.rb file from inside your standalone script.

Example:

#!/bin/env ruby

ENV['RAILS_ENV'] = "production" # Set to your desired Rails environment name
require '/path/to/railsapp/config/environment.rb'

# After this point you have access to your models and other classes from your Rails application

model_instance = MyModel.find(7)
model_instance.some_attribute = "new value"
model_instance.save
like image 93
ctcherry Avatar answered Nov 10 '22 04:11

ctcherry


I have to agree with David here. Use a migration for this. I'm not sure what you want to do, but running it from inside your environment is much, much more efficient then loading up the app environment manually. And since your initial post suggests you're only doing this once, a migration is the way to go:

rails g migration MigrateData

.. generates:

class MigrateData < ActiveRecord::Migration
  def self.up
    # Your migration code here
  end

  def self.down
    # Rollback scenario
  end
end

Of course, you will always want to perform this locally first, using some test data.

like image 25
Jaap Haagmans Avatar answered Nov 10 '22 05:11

Jaap Haagmans


Agree with everyone, for this specific case it sounds like migration will be way to go, however, to do this regularly, or write some other task/script that interacts rails app environment make rails generate a rake task for you! This gets saved with your rails app, and can be run again and again :)

Easiest way to generate a rake task 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!

like image 26
Shaunak Avatar answered Nov 10 '22 03:11

Shaunak