← Back to Upcase

Primary Key in Rails


(Sidd Tewari) #1

If I specify the primary key is my migration, like so:

create_table :customers, primary_key: “customer_id” do |t|

What else would I need to add to my models to make everything work smoothly and seamlessly while adhering to the Rails way?

For reference, I’m wondering if I need to add :id => false or the more important self.primary_key in the model.


(Sean Griffin) #2

You’ll need to have this in your model:

class Customer < ActiveRecord::Base
  set_primary_key :customer_id
end

(Jon Yurek) #3

You don’t need to add :id => false, because that will turn the primary key off completely. You will need to set the primary key with self.primary_key = 'customer_id' in your model. As far as I’m aware that should be enough.


(Sidd Tewari) #4

I just added this to my models: self.primary_key = “customer_id” - does that work just as well?


(Jon Yurek) #5

Yes it will. set_primary_key is deprecated at this point in favor of self.primary_key = "key".


(Sidd Tewari) #6

Thanks guys!

Just updated all my models. Though surprisingly everything was working seamlessly even without this key line.