2015-10-03 34 views
1

我想创建生成模型,看起来像这样一个迁移:创建独特的范围迁移

# 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问题。


例子:

名称:悉尼,COUNTRY_CODE:澳大利亚

名称:悉尼,COUNTRY_CODE:德国

应该让

名称:悉尼,country_c颂:澳大利亚

名称:悉尼,COUNTRY_CODE:澳大利亚

不应该被允许

回答

2

一来强制唯一横跨两列数据库的方法是创建这些列的唯一索引。

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

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 
+1

**您无法从命令行创建此类型的迁移** –