Monday, February 2, 2015

Updating a Rails Model with a Non-default Primary Key

In my last post, I talked about creating a Rails model with a non-default primary key. You can create new instances of the model with no problem, but what happens when you want to update an instance of the model?
 TypeError: nil is not a symbol nor a string  
Oh no!!!!

Fortunately, there is an easy fix. You just have to specify the column name of the primary key from within the model.
 class BearHabitat < ActiveRecord::Base  
   self.primary_key = 'bear_id'  
Now you should be able to update your model within your code with no problem. Why does this happen in the first place? My guess is that somewhere within ActiveModel, it assumes that the primary_key field is set. Since your migration set id to false, this value gets defaulted to nil. If you don't manually set it, ActiveModel gets sad. Now you can make ActiveModel happy again.