Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 在RoR架构中添加主键约束_Mysql_Ruby On Rails_Sqlite_Primary Key - Fatal编程技术网

Mysql 在RoR架构中添加主键约束

Mysql 在RoR架构中添加主键约束,mysql,ruby-on-rails,sqlite,primary-key,Mysql,Ruby On Rails,Sqlite,Primary Key,在我们的web应用程序中,我们的表在ID字段中有一个“GUID”ID。 通过研究用于创建DB的实际SQL代码,我们发现ID实际上没有作为主键延迟。似乎没有强制唯一性,也没有创建索引 这感觉很糟糕,所以我们想解决这个问题。我们的目标只是将ID字段设置为“主键” 下面是schema.rb的一个示例 create_table "projects", :id => false, :force => true do |t| t.string "id" t.string

在我们的web应用程序中,我们的表在ID字段中有一个“GUID”ID。 通过研究用于创建DB的实际SQL代码,我们发现ID实际上没有作为主键延迟。似乎没有强制唯一性,也没有创建索引

这感觉很糟糕,所以我们想解决这个问题。我们的目标只是将ID字段设置为“主键”

下面是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
在开发中,我们使用SQLite3数据库,而在生产中,我们依赖MySQL

我知道在现有的SQLite3DB上添加这样的约束是不可能的,但是如果需要的话,我准备放弃它并重新创建它。 如果可能的话,我希望避免删除MySQL数据库,但是如果确实有必要,我可以对其进行备份,并将数据插入到新的模式中


最好的方法是什么?(Rails V3.2.6)

如果要在Rails中设置非标准主键,应该查看

在您的迁移使用中,就像您已经做的那样

:id => false 
然后在您的模型中尝试以下方法

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

如果您只想确保唯一性,可以使用如下ActiveRecord验证:

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

希望这能有所帮助。

我知道这对实际的组合键是如何有用的,但在我的情况下,这与使用::validate\u university\u of:id有什么不同?如果可能的话,我希望在DB级别强制执行唯一性,而不是在模型级别。
validates_uniqueness_of :your_id, :message => "ID needs to be unique"