Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

ruby - how to add a primary key to a table in rails

Hi I have a table in my rails app that doesnt have any id column or primary key. thats because this table was brought into my rails app from a previous app and the table is prepopulated with data. I now realize that without a integer primary key, rails cannot display edit and show views in the browser. So i ned to add a id column to my database that is a primary key and that autoincrements.

Based on my googling, I came across a few posts about creating primary keys for a table but nothing that was complete.

So Im wondering if someone can give me a hand here. So far what I know is in order to change the table one must write a migration and then run it. The command that needs to be run for adding a id column is as follows:

rails generate migration add_id_to_businesses id:primary_key

However after running this command no new column is added to my database. Im not sure how to proceed.. How do I add a new column to my database?

Would really appreciate a hand..... Thanks,

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
rails g migration add_id_to_products id:primary_key

      invoke  active_record
      create    db/migrate/20120310085527_add_id_to_products.rb

Migration file should look like -

   # db/migrate/20120310085527_add_id_to_products.rb
   class AddIdToProducts < ActiveRecord::Migration
     def change
        add_column :products, :id, :primary_key
     end
   end

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...