简体   繁体   English

在RoR模式中添加主键约束

[英]Add a primary key constraint in a RoR schema

In our web application our tables have a "GUID" ID held in an id field. 在我们的Web应用程序中,表的ID字段中保存有一个“ GUID” ID。 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. 通过研究用于创建数据库的实际SQL代码,我们发现ID实际上没有作为主键被延迟。 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" 我们的目标只是将ID字段设置为“主键”

Here is a sample of our schema.rb 这是我们的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. 在开发中,我们使用SQLite3数据库,而在生产中,我们依赖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. 我知道不可能在现有的SQLite3数据库上添加这样的约束,但是我准备删除它并在需要时重新创建它。 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. 如果可能,我希望避免删除MySQL DB,但如果确实需要,可以备份它,并将数据插入新的架构中。

What would be the best approach to do it ? 最好的方法是什么? (Rails V3.2.6) (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 如果要在Rails中设置非标准主键,则应查看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. gem正在覆盖默认的Rails行为,因此要使用的密钥由create语句设置。 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 另一种方法是在迁移中使用:primary_key选项

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

or, 要么,

if you just want to ensure uniquness, you can use ActiveRecord validations like this: 如果您只想确保唯一性,则可以使用ActiveRecord验证,如下所示:

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

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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