Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom non auto-incrementing ActiveRecord "id" column possible?

I'd like to be able to use a custom id (instead of the auto-incrementing default ones) for a Rails model. Basically, all the ids will be iTunes store ids, which are just long integers. Is it possible to turn off the default auto-incrementing ids and require that one be set? These ids will also be used as foreign keys in other models.

like image 427
markquezada Avatar asked Nov 20 '10 09:11

markquezada


2 Answers

Something like this:

create_table :blah, {:id => false} do |t|
  t.int :my_custom_int_id
end
execute "ALTER TABLE blah ADD PRIMARY KEY (my_custom_int_id);"
like image 100
Alex Avatar answered Oct 19 '22 13:10

Alex


You can manually set the id before you save the model.

a = Model.new
a.id = 8888 #from itunes
a.save

However, you should consider a separate field called itunes_id instead of this approach.

like image 23
Chandra Patni Avatar answered Oct 19 '22 11:10

Chandra Patni