using different field as primary key instead of default primary key in rails

1) while creating table (migration file)  mention “id as false”  as follows

class CreateRadusergroups < ActiveRecord::Migration
def change
create_table :radusergroups, :id => false do |t|
t.integer :priority
t.integer :image_id
t.string :username, :groupname
end
end
end

2) setting another primary key have two options

1)  By Model class  code

when you have table named images that contained a field named image_id. the code will be

class Image < ActiveRecord::Base
set_primary_key “image_id”
end

2) in migration file adding one more line as follows

class CreateRadusergroups < ActiveRecord::Migration
def change
create_table :radusergroups, :id => false do |t|
t.integer :priority
t.integer :image_id
t.string :username, :groupname
end
end
execute “ALTER TABLE radusergroups ADD primary key(image_id)”
end

Even though we have a different primary key field name. still we can refer it as  “id”

www.klairvoyant.in

Advertisements
This entry was posted in rails, ROR, ruby on rails, web development and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s