Using the model to insert records without a running rails application

Hey,

I want to insert new records manually with a little ruby script and I
want to use the corresponding rails models beyond the running rails
application. How do I manage this? Is there a way to fill up some
tables using a kind of yml-files like you have in the testing
environment?

Thanks for your suggestions!
ms

On Mon, Jul 6, 2009 at 8:38 AM, ms[email protected] wrote:

I want to insert new records manually with a little ruby script and I
want to use the corresponding rails models beyond the running rails
application.

Use script/runner to execute your script in your Rails environment.
And of course you can load data from YAML, CSV – whatever kind
of files you like.

HTH,

Hassan S. ------------------------ [email protected]
twitter: @hassan

Hi –

On Mon, 6 Jul 2009, ms wrote:

Hey,

I want to insert new records manually with a little ruby script and I
want to use the corresponding rails models beyond the running rails
application. How do I manage this? Is there a way to fill up some
tables using a kind of yml-files like you have in the testing
environment?

I imagine there’s a script or rake task out there that does this, but
if you want to roll your own, it’s not hard.

Here’s a mini-example. Create a file called (say) users.yml, like
this:

one:
name: Emma Peel
email: [email protected]
two:
name: John Steed
email: [email protected]

Then create a file called read_records.rb (or whatever):

users = YAML.load(File.read("/path/to/users.yml"))
users.each do |tag,hash|
User.create(hash) # give or take error checking
end

Then run it using script/runner:

cd my_rails_app_directory
./script/runner /path/to/read_records.rb

The runner script will load your application environment (development
by default), so it will know what User is and it will already have
YAML loaded.

And of course you can include the YAML in the script file instead, or
just create hashes directly, and so on.

As I say, there are probably more turnkey-ish ways to do it already
out there somewhere, though I find it pretty turnkey-ish anyway.

There’s also rake db:fixtures:load, if you happen to have the sample
data you want already in the test fixtures.

David


David A. Black / Ruby Power and Light, LLC
Ruby/Rails consulting & training: http://www.rubypal.com
Now available: The Well-Grounded Rubyist (http://manning.com/black2)
Training! Intro to Ruby, with Black & Kastner, September 14-17
(More info: http://rubyurl.com/vmzN)

ar_fixtures can do some of this kind of stuff - may be worth taking a
look at.

–Matt J.

Thank you both - this was exactly the hint I needed! :slight_smile:

Cheers,
ms

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs