2

What is the proper way to create a table in rails via a migration in which the primary key is a string instead of an int?

I've tried setting primary_key as @oldergod suggested in the answer below but baz seems to get set to an int still:

class CreateFoos < ActiveRecord::Migration
  def change
    create_table :foos, primary_key: 'baz' do |t|
    end
  end
end

UPDATE

I've since tried

class CreateFoos < ActiveRecord::Migration
  def change
    create_table :foos, primary_key: false do |t|
      t.string :baz
    end
  end
end

which gets me a little closer but still missing the PRIMARY index on the column. I've tried add_index :foos, :baz, type: :primary but this generates the following error:

SQLite3::SQLException: near "primary": syntax error: CREATE primary INDEX "index_foos_on_baz" ON "foos" ("baz")/Users/kyledecot/.rvm/gems/ruby-1.9.3-p392/gems/sqlite3-1.3.8/lib/sqlite3/database.rb:91:in `initialize'

It seems like this should work after looking at http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_index_options

Kyle Decot
  • 20,715
  • 39
  • 142
  • 263
  • See this [answer](http://stackoverflow.com/questions/1200568/using-rails-how-can-i-set-my-primary-key-to-not-be-an-integer-typed-column) it goes into a decent amount of detail as to how the generator works and how to work around it. – engineersmnky Sep 23 '13 at 13:42
  • That answer has the side effect of `rake db:schema:load` not working correctly and creating `int` columns. It will only work properly if using `rake db:migrate`. – Kyle Decot Sep 23 '13 at 14:16
  • You are trying to change the intended behavior of Rails side effects are to be expected. Why are you interested in doing this anyway? What negative effect does having an integer primary key have? – engineersmnky Sep 23 '13 at 14:24

1 Answers1

-1

What's different if it's a string? See the create table doc.

create_table :foos, primary_key: 'baz' do |t|
  t.column :baz, :string
end

Also note that this just sets the primary key in the table. You additionally need to configure the primary key in the model via self.primary_key=. Models do NOT auto-detect the primary key from their table definition.

oldergod
  • 15,033
  • 7
  • 62
  • 88
  • I've updated my question w/ what I have tried. `baz` is being set to an integer still. This is the expected behavior as you can see in the `create table` docs you linked me to near where it says "Rename the primary key column". Their generated output is `guid int(11)` – Kyle Decot Sep 23 '13 at 13:34
  • @KyleDecot updated my answer. Don't you define your column inside the create_table block? – oldergod Sep 23 '13 at 13:48
  • I tried that which gave me the message `you can't redefine the primary key column 'baz'. To define a custom primary key, pass { id: false } to create_table.` I then set it to false which created the column but w/ no index. I've updated my question w/ the current failure. – Kyle Decot Sep 23 '13 at 14:16