weewar.com corner

script/console hack to load fixtures

Posted by railsbros_dirk
on Wednesday, February 27

This week I found out that the sexy fixtures were indeed really sexy. The so far pretty random ids you got with the new fixtures style (omitting the id) isn't that random after all.

This again a pretty nice example for RTFM, cause all those blogs I've read about Rails 2.0 told you that you don't have to worry about the id of your test data. As far as I can recall they all spoke of being generated, but after reading the API docs it is more something like being transformed. They absolute value of the hash of the fixtures label. And because all your labels have to be unique all your ids will be unique.

Now knowing that I came along with a little .irbrc hack to use something like this in your Rails console:

  
User.find('my_fixture_user')
  

and it will get you the database row with the id according to that string. Of course you must have loaded your fixtures into the current environment.

For me who is an excessive user of the Rails console this is a really handy feature.

Enough of the talking, show me the code already. - OK, here you go ...

  
if ENV['RAILS_ENV']
  require 'active_record'
  ActiveRecord::Base.class_eval do
    class << ActiveRecord::Base
      alias_method :classic_find_from_ids, :find_from_ids

      private
        def find_from_ids(ids, options)
          ids.collect! { |id| id.to_i <= 0 ? id.hash.abs : id }
          classic_find_from_ids(ids, options)
        end
    end
  end
end
  

Enjoy it!

UPDATE: Andi pointed out that you can omit the assignment of the local id variable within the block. So I updated the code snippet. Thanks Andi!

Comments

Leave a response