2015-10-03 31 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

**您無法從命令行創建此類型的遷移** –