How to create a seed script in ruby using DataMapper to populate db?

824 views
Skip to first unread message

supamanu

unread,
Mar 2, 2012, 2:03:40 PM3/2/12
to sinatrarb
Hello

I'm building a simple sinatra app using DataMapper as my ORM and pgsql
as both my dev and prod db (pushing to heroku).

This is all pretty new stuff to me. What I can't figure out is how to
build a seed script in ruby so that I can quickly re-populate my db
locally whenever I destroy it to make changes in my model/underlying
tables (i'm iterating a lot as I find my way around associations).

The thing is once my server is running and I'm on my web page, I don't
know where to place the seed file or how to call it. Can I just open a
terminal window and e.g. run a 'seed.rb' file? Will all the
dependencies already be loaded since my app is running?

I guess what i'm trying to say is that my mindset is 'everything goes
through a url with get/post etc' and I can't reconcile that with 'oh,
i need to run a script to fill some tables'. And I would rather keep
everything in ruby using DataMapper and not have to use psql commands
to do the seeding.

Thanks for you help.

Mike Abner

unread,
Mar 2, 2012, 2:21:12 PM3/2/12
to sina...@googlegroups.com
1.) write a class that does the seeding with a seed method. e.g. class DbSeeds; def self.seed; DO IT; end; end;
2.) run irb from your project root
3.) require your 'root' file. e.g. MyApp.rb (i'm assuming this app is requiring all your models and everything.  If it isn't, require the file that does)
4.) run the method that does the seeding in the seeds class.  e.g. DbSeeds.seed  (assuming seeds deletes the existing data first, if not…do that first)
5.) there is no 5

Mike

supamanu

unread,
Mar 2, 2012, 5:02:50 PM3/2/12
to sinatrarb
Mike, you rock! Thanks a bunch.

Mike Abner

unread,
Mar 2, 2012, 5:17:37 PM3/2/12
to sina...@googlegroups.com
Glad to help!

Mike

--
You received this message because you are subscribed to the Google Groups "sinatrarb" group.
To post to this group, send email to sina...@googlegroups.com.
To unsubscribe from this group, send email to sinatrarb+...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/sinatrarb?hl=en.

ericgj

unread,
Mar 2, 2012, 6:59:07 PM3/2/12
to sinatrarb
Besides IRB, there's also tux which is like the Rails console but even
nicer.
http://tagaholic.me/2011/04/10/tux-a-sinatra-console.html
Reply all
Reply to author
Forward
0 new messages