简体   繁体   中英

Add a primary key constraint in a RoR schema

In our web application our tables have a "GUID" ID held in an id field. By investigating the actual SQL code that is used to create the DB, we saw that our ID are actually not delayed as primary keys. No uniqueness seems enforced and no index is created.

This feels bad so we would like to fix that. Our objective is simply to set our ID field as "primary key"

Here is a sample of our schema.rb

 create_table "projects", :id => false, :force => true do |t|
    t.string   "id"
    t.string   "name"
    t.string   "objective"
    t.datetime "created_at",                              :null => false
    t.datetime "updated_at",                              :null => false
    t.string   "client_account_id"
    t.string   "default_project_name"
    t.boolean  "quota_exceeded",       :default => false, :null => false
  end

In development, we are using SQLite3 databases, while in production, we are relying on MySQL.

I know that it is not possible to add such a constraint on an existing SQLite3 DB, but I am ready to drop it and recreate it if needed. If possible, I would like to avoid dropping the MySQL DB, but I can back it up if it is really necessary and insert the data in a new schema.

What would be the best approach to do it ? (Rails V3.2.6)

If you want to set a non-standard primary key in Rails you should have a look at the composite_primary_keys gem

In your migration use, like you already did,

:id => false 

Then in your model try the following

require 'composite_primary_keys'
class User < ActiveRecord::Base
  self.primary_keys = :your_custom_id
end

The gem is overriding the default Rails behavior so that the key you want to use is being set by the create statement. This way you also can use composite primary keys if you want to.

Another approach would be to use the :primary_key option in your migration

create_table "projects", :primary_key => 'your_id' do 
  ...
end

or,

if you just want to ensure uniquness, you can use ActiveRecord validations like this:

validates_uniqueness_of :your_id, :message => "ID needs to be unique"

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM