How to Add a Primary Key to a Table in Rails

Rails Migration Create Table Primary Key

I suppose you're using mySQL, so here is what you can try

create_table :global_feeds, {:id => false} do |t|
t.string :guid
t.text :title
t.text :subtitle
t.timestamps
end
execute "ALTER TABLE global_feeds ADD PRIMARY KEY (guid);"

If you're not on mySQL you should change the query in the execute command to work on your DB engine. I'm not sure if you can do that on SQLite though. And don't forget to put this line somewhere in global_feed.rb model:

set_primary_key :guid

Anyway you're getting the most out of Rails while you're sticking to its conventions. Changing primary key name and type might not be a very good idea.

how to add a primary key to a table in rails


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

How to add primary key to Rails?

In your migration file:

create_table :bookmarks, :primary_key => :bk_id do |t|
...
t.integer :bk_id
...
end

Do not forget to indicate it in your Model too:

class Bookmarks < ActiveRecord::Base
self.primary_key = 'bk_id'
end

Add primary key to an existing field in Rails

I ended up doing this:

execute('ALTER TABLE inventories ADD PRIMARY KEY (id);')

Rails: Add UUID Primary Key to Table in Database Already Using UUIDs as Primary Keys

Kept trying until this worked...

def change
add_column :products_questions, :id, :uuid, primary_key: true, default: -> { "gen_random_uuid()" }
end

How to set primary key in ruby on rails migration?

Don't do this. Use the built-in id field as the primary key. If you're going to use Rails, you should build your app the "Rails way" unless you have very good reason not to.

If you really want to do this, you can pass a :primary_key option to create_table:

create_table :customers, :primary_key => :idClient do |t|
# ...
end

You'll also need to tell your model the name of its primary key via self.primary_key = "idClient"

How to change primary key in rails migration file?

You could execute arbitrary SQL in your migration:

execute "ALTER TABLE `products` DROP PRIMARY KEY"

and then add the new column:

add_column :products, :id, :primary_key

See:

Remove Primary Key in MySQL

how to add a primary key to a table in rails

http://thinkwhere.wordpress.com/2009/05/09/adding-a-primary-key-id-to-table-in-rails/

http://api.rubyonrails.org/classes/ActiveRecord/Migration.html



Related Topics



Leave a reply



Submit