问题描述
我的 rails 应用程序中有一个表,它没有任何 id 列或主键.那是因为这个表是从以前的应用程序带入我的 rails 应用程序的,并且该表预先填充了数据.我现在意识到如果没有整数主键,rails 无法在浏览器中显示编辑和显示视图.所以我需要在我的数据库中添加一个 id 列,它是一个主键并且自动递增.
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.
所以我想知道是否有人可以帮助我.到目前为止,我所知道的是为了更改表,必须编写迁移然后运行它.添加id列需要运行的命令如下:
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,
推荐答案
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
这篇关于如何在rails中的表中添加主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!