Resetting password of Devise user from the database

I recently encountered a situation where I was trying to access a Rails application but:

  • I didn’t know the password for the admin user
  • The reset password functionality was not working
  • I had no access to a Rails console

Knowing the User model was using Devise, I set a password for a user on a dev environment to find the encrypted_password:

u = User.find(1)
u.update(password: 'password')

I could then use SQL to update the password on the prod environment:
UPDATE users SET encrypted_password = '$2a$10$qjBArbMLISBaUDMKdNM0KuZNPsRzPMIINMsPT.NhE9UrIYnErVF2S' WHERE id = 1;

Get database version in Rails

For one of my applications, I recently created a status report page which shows crucial information for debugging, including software versions, service connectivity and filesystem path writability. One of the items was a database version string, and the standard ActiveRecord interface does not support this concept. While version methods usually exist in the connection adapters, they are usually protected/private and have different naming conventions.

As the application can be run against multiple backends as well as on MRI or JRuby, I needed to check what adapter was in use, then query the database:

adapter = ActiveRecord::Base.connection.adapter_name
sql = case adapter
  when 'MSSQL'
  when 'MySQL', 'Mysql2', 'PostgreSQL'
  when 'OracleEnhanced'
  when 'SQLite'

Optimising index view performance

I recently came across a scenario where my index views in Rails were taking a long time to render when there were large data sets. The problem stemmed having a lot of data presented that were from models/tables other than the primary model/table of interest.

For example, an “asset” index view may have the following columns:

  • Name (from
  • Type (from
  • Site (from
  • Organisation (from
  • System (from
  • Status (from

The first (naive) approach I used was to query using eager loading:

Asset.includes(:type, {site: :organisation}, :system, :status)
     .search_by('', 'Pump')

Using a data set of around 500,000 items, rack-mini-profiler indicated this took about 6.7 seconds to render the action with 5.6 seconds of that consumed by the SQL query.

When investigating, I noticed this was using a single query with LEFT OUTER JOINs. I then forced ActiveRecord to use separate queries to load the related models by using Rails 4’s preload instead of includes and used joins instead of references to force ActiveRecord to use a more performant INNER JOIN:

Asset.preload(:type, {site: :organisation}, :system, :status)
     .search_by('', 'Pump')

This dropped the action render time to 1.7 seconds with 0.7 seconds consumed by the six SQL queries.

For my index views, I actually don’t need the entire object graph to be hydrated – I only really needed the names of the related object. So I tried using pluck, which returns an 2-dimensional array of values:

Asset.includes(:type, {site: :organisation}, :system, :status)
     .joins(:type).search_by('', 'Pump')
     .pluck(:name, '', '', '', '', '')

This actually increased the action render time to 2.1 seconds with 1.7 seconds consumed by ActiveRecord and the SQL query. The SQL query now uses LEFT OUTER JOINs again, which as we saw in the original case, is slow. But the differential between the total and SQL had decreased since ActiveRecord models did not have to be created.

While using the second approach would provide a significant speed boost without changing any code, I wondered if we could use a combination of the second and third approaches – use separate SQL queries instead of a single with LEFT OUTER JOINs and simply pass back an array and not have to hydrate ActiveRecord models.

The result: Preload Pluck.

On the same data set, Preload Pluck drops the action render time to 1.5 second with 0.7 seconds consumed by the SQL queries.

YMMV as the results above are for that particular data set, the queries I’ve used and the way my PostgreSQL database is setup.

Apache2 configuration for Rails

I recently had to stand up a Rails production server that used Apache2 as a reverse proxy. While it was relatively easy proxying requests to the Thin server using ProxyPass, assets would not show up, even with a DocumentRoot specified. It seems that ProxyPass proxies all requests, and the configuration needs to specifically ignore proxying certain requests using the exclamation mark syntax. The configuration looked like:

<VirtualHost *:80>
        DocumentRoot /var/www/app/public
        ProxyPassMatch ^/(assets/|(404|422|500)\.html|favicon\.ico|robots\.txt) !
        ProxyPass / http://localhost:3000/
        ProxyPassReverse / http://localhost:3000/

Selecting string literals in Rails 4 using PostgreSQL

I recently ran into an issue with Rails 4 using the PostgreSQL adapter (MRI) where selecting a string literal in a query would return a warning about an unknown OID.

This can be reproduced by running the following in Rails Console:

Rails.logger.level = 2
ActiveRecord::Base.connection.select_all("SELECT 'test'")

=> unknown OID: ?column?(705) (SELECT 'test')

This occurs both with and without column aliases.

705 is PostgreSQL’s code for an unknown type and in order to fix this, what we want to do is register the “unknown” type. Based on this blog post, I put the following code in an postgres_oids.rb initializer:

# Treat any unknown types (e.g. string literals) as text
ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::OID.alias_type 'unknown', 'text'

Using Rails’ descendants in development

Rails provides a nice method descendants that returns all subclasses for a specified class. However, config.cache_classes = false is a default setting in development.rb (for the ability to reload classes on the fly) and as this tells Rails not to load classes until they are referenced, then calling descendants will generally return an empty array not the expected subclasses.

To be able to use descendants in development, you can add the following code to development.rb:

config.eager_load_paths += Dir['path/to/files/*.rb']
ActionDispatch::Reloader.to_prepare do
  Dir['path/to/files/*.rb'].each {|file| require_dependency file}

The first line tells Rails to load these particular files when Rails first starts up. The rest of the code tells Rails to require these particular files (including any new files/classes) on each request.

Note: if your path/to/files isn’t one of the standard directories that Rails watches (to trigger the reloader), you will need to add it to config.watchable_dirs:

config.watchable_dirs['path/to/files/'] = [:rb]

Reducing Rails asset precompile times on JRuby

Rails asset precompile times on JRuby are considerably slower compared to MRI. I came across this post which provided suggestions on speeding up the asset precompile task.

Using the following options – using Node.js instead of therubyrhino for JS compilation, forcing the JVM to 32 bit (although this can be omitted on a 32 bit JVM) and not using JIT compilation – cut my asset precompile time from 4 mins 37 secs to 2 mins 8 secs. Using Node.js contributed to the majority of that time since I’m using a 32 bit VM.

EXECJS_RUNTIME='Node' JRUBY_OPTS="-J-d32 -X-C" rake assets:precompile