开发者

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 colum开发者_Go百科n 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.


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


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.


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!


Seeding data:

http://railscasts.com/episodes/179-seed-data

Adding data with migrations

http://railscasts.com/episodes/23-counter-cache-column

Working with Rake Tasks

http://railscasts.com/episodes/66-custom-rake-tasks

I prefer to use migrations for adding some data in your case.


If it's a one-time thing, use a migration.

If this is something that needs to be done multiple times, use a rake task for it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜