Friday, July 20, 2012

Speed up updates of large datasets/records in Rails

Suppose we have 10,0000 users. We can do the following

User.find_each |user|
  user.update_attributes(status: 'active')
end
But that takes a long to complete. Executing raw sql over ActiveRecord speeds things up tremendously.

User.connection.execute("update users set status = 'active'")

Monday, July 16, 2012

Get ruby constant from string


UserType.const_get('foo'.upcase)

Rails generator to generate rspec files by default instead of test unit

Just add rspec-rails into the Gemfile. Nothing else needed.

group :development, :test do
  gem 'rspec-rails'
end

Tuesday, June 19, 2012

Sync database from production db on Heroku

One could use the awesome taps gem like so:

heroku db:pull

However that gets real slow real quick so I had to use PG Backups addon instead

# Install heroku addon
heroku addons:add pgbackups

# Capture latest db snapshot on heroku
heroku pgbackups:capture

# Get download url and enter it in browser with a heroku login session
heroku pgbackups:url {latest_backup_name}

# Restore pg dump into local PostgreSQL database
pg_restore -d {db_name} ~/Downloads/{latest_backup_name}.dump

Starting PostgreSQL server on OSX


pg_ctl -D /usr/local/var/postgres start

Thursday, June 14, 2012

Force remove files in OSX Trash


rm ~/.Trash/xxx

Monday, June 11, 2012

Rails number_to_percentage always 0

This is a silly mistake that I often make.

# This always return a big fat zero
number_to_percentage(User.count/Signup.count)

# Remember to have divide by floats!
number_to_percentage(User.count.to_f/Signup.count.to_f)