【问题标题】:Create migration with uniqueness to a scope创建对范围具有唯一性的迁移
【发布时间】:2015-10-03 20:38:30
【问题描述】:

我想创建一个生成如下模型的迁移:

# Table name: cities
# 
#  country_code :text
#  created_at   :datetime         not null
#  id           :integer          not null, primary key
#  name         :string
#  updated_at   :datetime         not null
#

class City < ActiveRecord::Base
  validates :name, presence: true, uniqueness: {:scope => :country_code, 
    message: "A name and country already exists for this entry" }

end

如何创建standalone migration 来创建此模型?

我可以让:name 在整个表格中独一无二:

rails g migration CreateCitites name:string:uniq country_code:text timezone:text

我在创建 :name 相对于 :country_code 的唯一性时遇到问题。


例子:

名称:悉尼,国家代码:澳大利亚

名称:悉尼,国家代码:德国

应该允许

名称:悉尼,国家代码:澳大利亚

名称:悉尼,国家代码:澳大利亚

不应允许

【问题讨论】:

    标签: ruby-on-rails activerecord migration rails-console


    【解决方案1】:

    在数据库中的两列之间强制执行唯一性的一种方法是在这些列上创建唯一索引。

    您无法从命令行创建这种类型的迁移,但您可以在迁移文件生成后对其进行更改。

    def up
      create_table :cities do
        # etc.
      end
    
      # Add your index declaration here, after "create_table"
      add_index :cities, [:contry_code, :name], unique: true
    end
    

    【讨论】:

    • 您不能从命令行创建这种类型的迁移
    猜你喜欢
    • 2016-06-02
    • 2017-06-23
    • 1970-01-01
    • 2011-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    • 2014-01-31
    相关资源
    最近更新 更多