undefined method `relation’ for nil:NilClass on Heroku

I host almost 100% of my open source projects on Heroku, it’s amazing how easy it is to setup and how “out-of-your-way” they are.

Today, while working on one of my open source project I encountered this error:

plan.update_attributes!({:contract_id_with_trial => 2133290})
NoMethodError: undefined method `relation' for nil:NilClass
/app/.bundle/gems/ruby/1.9.1/gems/arel-2.0.9/lib/arel/crud.rb:12:in `update'
/app/.bundle/gems/ruby/1.9.1/gems/activerecord-3.0.3/lib/active_record/persistence.rb:255:in `update'
/app/.bundle/gems/ruby/1.9.1/gems/activerecord-3.0.3/lib/active_record/locking/optimistic.rb:77:in `update'
/app/.bundle/gems/ruby/1.9.1/gems/activerecord-3.0.3/lib/active_record/attribute_methods/dirty.rb:68:in `update'
view raw heroku_error This Gist brought to you by GitHub.

It was right after I deployed and migrated the database.

After about 5 minutes of head scratching I came across an answer on stackoverflow saying you have to restart your app after a migration for it to pick up on schema changes.

Had a DAH! moment there :-)

The simplest Enum you will ever find for your ActiveRecord models

I have been using a really useful snippet for a while now.

While dropping it today into a project I realized just how powerful it is:

  1. it’s a drop-in and will work on any project
  2. it’s database agnostic
  3. it’s dead simple
  4. it’s not sensitive to enum changes
  5. and more and more

Just as an into, an enum is a way to have string represented as integers in your database.

Why?

Because integers are much faster to index and query (at least on mysql).

MySQL has an enum solution but ActiveRecord can’t really use it without some nasty hacking and it’s really messy when you want to add another param.

Enough Said, here’s the snippet

  STATUS = { pending: 0, active: 1, inactive: 2, deleted: 3 }

  def status
    STATUS.key(read_attribute(:status))
  end

  def status=(s)
    write_attribute(:status, STATUS[s])
  end
view raw account.rb This Gist brought to you by GitHub.

This gives you the ability to work with the Account model like so:

>> account = Account.first
  Account Load (0.2ms) SELECT `accounts`.* FROM `accounts` LIMIT 1
=> #<Account id: 4, name: "KensoDev", subdomain: "kensodev", user_id: 6, created_at: "2012-05-08 16:06:31", updated_at: "2012-05-08 16:29:11", logo_file_name: nil, logo_content_type: nil, logo_file_size: nil, logo_updated_at: nil, token: "5022N7VSAD", plan_id: 1, project_count: 1, contact_count: 1, quota_used: 0, notification_interval: nil, billing_token: "", status: 1>
>> account.status
=> :active
>> account.status = :pending
=> :pending
>> account.save
  SQL (0.1ms) BEGIN
  Account Load (0.3ms) SELECT `accounts`.`id` FROM `accounts` WHERE (`accounts`.`subdomain` = BINARY 'kensodev') AND (`accounts`.id <> 4) LIMIT 1
User Load (0.2ms) SELECT `users`.* FROM `users` WHERE (`users`.`id` = 6) LIMIT 1
Plan Load (0.2ms) SELECT `plans`.* FROM `plans` WHERE (`plans`.`id` = 1) LIMIT 1
User Load (0.3ms) SELECT `users`.`id` FROM `users` WHERE (LOWER(`users`.`email`) = LOWER('avi@kensodev.com')) AND (`users`.id <> 6) LIMIT 1
[paperclip] Saving attachments.
AREL (0.2ms) UPDATE `accounts` SET `status` = 0, `updated_at` = '2012-05-08 16:29:40' WHERE (`accounts`.`id` = 4)
[paperclip] Saving attachments.
SQL (1.5ms) COMMIT
=> true
>>

As you can see, it’s being persisted into the database as an integer, but you work with symbols/strings which is much nicer and cleaner.

Showing the git commit SHA that is currently deployed

I cannot count how many times I (or others) have asked the following question:

What is the difference between master and the production version?

We deploy about 3-5 times a day and we merge code about twice as much into master (some days, even more then that).

We deploy to servers with Capistrano, Capistrano has a very useful feature to write a REVISION file to the root of the project, this file contains a single line with the commit sha.

So, I thought I might set up a controller that will read this file and display it when I want.

So, I spec’d it out:

describe :git_sha do
  it "should read the file correctly" do
    controller.stub!(:current_user).and_return(nil)
    File.should_receive(:open).with("#{Rails.root}/REVISION").and_return(stub(read: "aaa"))
    get :git_sha
    response.body.should == "aaa"
  end
end

And this is the controller code:

def git_sha
  revision = File.open("#{Rails.root}/REVISION").read.strip.to_s
  render :text => revision
end

Pivotal Tracker Git integration with ease

This post makes 2 assumptions

  1. You are working with Git
  2. You are working with Pivotal Tracker

At Gogobot, we work with Pivotal Tracker (for various reasons).

Pivotal Tracker has very good Git integration, when you commit (and push), the commits can show up as comments to the story.

Another very good thing is that you can change the status of a story just by a commit, you can finish, deliver or anything else you might want.

Usually, you need to add the story id (#12123123) to the commit message yourself, obviously, I never remember to do that.

So, the link in the bottom is a gem that integrates git with Pivotal Tracker very easily and effortlessly.

highgroove/git_tracker.

It has a very good README so keep on reading there.

Decorating Devise’s current_user with Draper – Ariejan.net

Link

A great trick to decorate the current_user method from devise using Draper.

IMHO it’s actually applicable to any authentication system out there that is using current_user but that requires some testing.

Decorators are an awesome way to remove logic from the view or the models, so the models have real business logic and the rest can be “decorated” with another class.

If you are looking for more information about decorators, Ryan Bates has a great screencast about it here: http://railscasts.com/episodes/286-draper

Enjoy

Decorating Devise’s current_user with Draper – Ariejan.net.

A Baseline for Front-End Developers – Adventures in JavaScript Development

Link

I stumbled upon this terrific post on Twitter.

This post goes into details (very deeply) about what it takes to be a Front End developer these days.

The amount of things and tools you need to know are overwhelming.

I recommend taking the time and reading it, it’s long, but worth every second you put into it.

A Baseline for Front-End Developers – Adventures in JavaScript Development.

Find the source location of a method in your project

Ruby/Rails project sometimes make it hard to find the source location of a method.

Sometimes, Duck typing, meta-programming and just plain bad design make it really hard to find where a method was defined and how.

Luckily, there’s an easy way around this.

So, here’s an example.

A few moments ago, I came across this line:

!!current_user.toggle_follow!(user)

First thing I did (obviously) was going to the user class and searching for this method. Obvious enough (or this post would not exist) I could not find it.

I immediately realized it’s being defined by some cache mechanism we have.

So, I opened up a console and typed this:

u = User.find(some_user_id)
u.method(:toggle_follow!)
view raw gistfile1 This Gist brought to you by GitHub.

And it returned

 => #<Method: User#toggle_follow!>
view raw gistfile1 This Gist brought to you by GitHub.

So, the method IS defined on the user somewhere, you can see exactly where like so:

u.method(:toggle_follow!).source_location
view raw gistfile1 This Gist brought to you by GitHub.

This will give you an exact location where the method is defined, I found this line:

toggle_method_name: "toggle_#{options[:method_verb]}!"
view raw cache_list.rb This Gist brought to you by GitHub.

This trick saves me time, hope it will save you some browsing around helplessly, especially in bigger non-single-dev projects

EDIT: 12 APR 2012 10:51PM
I posted a link to this post in the dev chat room on Campfire.

Steve, had an awesome comment:

Campfire conversation

We are using Octopus gem in our application (Gogobot), this gem is used to connect to databases with master/slave architecture.

Just as a general warning, you may get some results like that. but if you follow the source location, it’s usually a very good hint of where the method is actually defined and in any case, I think those Proxy situations are rare.

Awesome comment nonetheless, so I though I might update the post with it.

EDIT: 12 APR 2012 11:01PM

Jonathan Jackson replied to me on twitter, he said, that if you are using Pry (which you should) you can actually do it even better.

if you open up the console and do:

user = User.find(some_user_id)
edit-method user.toggle_follow!

view raw pry.rb This Gist brought to you by GitHub.

This will open up the default editor (Vim in my case) in the exact location where the method is defined and you are able to edit it in place.

Another awesome comment that was worth a post update :-)