Santosh
Santosh

Reputation: 984

Rails 4 migration: Create mysql table with primary key but without auto_increment

possible duplicate How to turn off auto_increment in Rails Active Record

New to rails, I want to create a fm_zipcodes table zipcode as primary key but I don't want extra auto_increment. I have tried different ways but none of them working for me and auto_increment not reflecting in db/schema.rb file.

create_table :fm_zipcodes, :primary_key => :zipcode do |t|
  t.integer :state_id, null: false
  ..
end

close answer https://stackoverflow.com/a/17960388/1093542

Upvotes: 0

Views: 126

Answers (2)

towonzhou
towonzhou

Reputation: 9

create_table :fm_zipcodes do |t|
  t.integer :zipcode, null: false
# ...
end
add_foreign_key :fm_zipcodes, :zipcode

more infomation please see http://api.rubyonrails.org/?q=add_foreign_key

Upvotes: 0

spickermann
spickermann

Reputation: 106802

I would do something like this:

# in your migration
def up
  create_table :fm_zipcodes, id: false do |t|
    t.integer :zipcode, null: false
    # ...
  end
  add_index :fm_zipcodes, :zipcode, unique: true
end

# in your FmZipcode model
self.primary_key = 'zipcode'

Upvotes: 1

Related Questions