http://podloni.co.cc Rebecca’s Ramblings » 2007 » June

Archive for June, 2007

How to get references, functions etc into your Rails test database

Monday, June 25th, 2007

Your rails app comes with 2 tasks to clone your database structure into the test database: db:test:clone, which does everything through ruby, and db:test:clone_structure, which dumps the SQL needed to recreate the database structure, then reloads it, in a DB-specific fashion. You can switch which version is run by the db:test:prepare task in environment.rb.

Find this bit:

# Use Active Record's schema dumper instead of SQL when creating the test database
# (enables use of different database adapters for development and test environments)
# config.active_record.schema_format = :ruby

Uncomment the last line shown above, and replace :ruby with :sql - that’s it!

If, like me, you’re using postgres databases, this does the trick - now db:test:prepare dumps the structure of your dev/production database using pg_dump -s … and loads it into the test database using psql.

A couple of caveats:

  • If you’re using functions written in a language that needs to be created after a new database is created, you must connect to your test database as a superuser, as only superusers can add languages.
  • If you’re using views in MySQL, the views are carefully removed from the dumped structure, so won’t be in your test database.

Running rake in production mode

Monday, June 18th, 2007

This is the second time now that this has had me tearing my hair out. Last time, I couldn’t work out how to get rake db:migrate to operate on the production database. After a while on Google, I managed to find:

%> rake --require=config/environment.rb db:migrate

It worked like a treat, even on the Windows server my app’s deployed on (though with \ as the path separator, not /).

Until now, that is.

I’ve just switched to using the paginating_find plugin for paging result sets, as it allows me to use all the find options, unlike the rails default pagination. It works fine in both development and production, and rake is happy in development mode. It doesn’t like the command above, though, if you happen to call the find method in your migration. For some bizarre reason, the find method aliasing goes wrong, and you get an infinite loop. The overwritten find method is supposed to call the original find method, but ends up calling itself recursively instead.

Back to Google… nothing on this problem that I could find.

Rethink: it must be something with the way production mode is specified, since it’s only a problem when running rake like this.

Back to Google again: this time to look for alternative methods to specify that rake should use the production environment. Finally found a way, thanks to a post on a TextDrive forum:

%> RAILS_ENV=production rake db:migrate

That solves the problem on Linux, how about on Windows?

%> set RAILS_ENV=production
%> rake db:migrate

Sorted!