Tag Archives: ActiveRecord

Making ActiveRecord faster by NOT indexing

Usually one of the first things I read about on how to speed up ActiveRecord is to index my columns to speed up the lookup of items. “Of course!” But could indexing too much be harmful

Essentially, if your column is an enum, then indexing it could actually cause MySQL to do more work. Why? Because the data set is so large, the MySQL ends up doing a full scan. So things like keeping track if something is active (1 or 0) then you can expect indexing to hurt.

So how does this effect ActiveRecord? Well, if you’re keeping track of whether a user is active or not you would not want to index that column alone. Nor would you want to index a type column if you were using single table inheritance, again, because there isn’t a lot of variance in the type.

So make sure that you index the right things, like IDs and leave the enum-like columns alone.

Trusting in Exceptions To Do What They Do

Nobody likes to see exceptions when running an application; it means something went wrong and you should have been on top of it. But with that, often times I find people will write code to prevent exceptions rather than just allowing them to occur and then using it in their favor.

Take this bit of ruby code in a rails controller as an example:

class ArticlesController < ApplicationController
  def show
    @article = Article.find(params[:id])
  end
end

That’s pretty solid, but what happens if someone passes in an ID that does not exist? Well in rails’ production mode, it would return a 404 error

Makes sense! That article doesn’t exist, so it can’t be found. I have dabbled with a little SEO(Search Engine Optimization) and usability and just a 404 isn’t cutting it for me. I think we can redirect our user back on a right track. For one, we know the user is trying to read an article, so why not redirect the user to a list of all the articles and give them a little warning?

Continue reading