基于 2 列定义唯一的主键 [英] Define a unique primary key based on 2 columns
问题描述
我想为基于 2 列的记录定义唯一键:'id' 和 'language'
I would like to define a unique key for records based on 2 columns : 'id' and 'language'
让用户提交以下字符串:id=1 语言=en 值=blabla 英语id=1 language=fr value=blabla 法语
to let the user submits the following strings : id=1 language=en value=blabla english id=1 language=fr value=blabla french
我尝试使用 set_primary_key 和 add_index 但它没有用 ( add_index :words, ["id", "language_id"], :unique => true )
I tried to use set_primary_key and also add_index but it didn't work ( add_index :words, ["id", "language_id"], :unique => true )
我有以下模型:
class Word < ActiveRecord::Base
belongs_to :dictionnary
belongs_to :language
attr_accessible :lang, :rev, :value, :dictionnary_id, :language_id
validates :value, :uniqueness => true
end
还有这个
class Language < ActiveRecord::Base
has_many :words
attr_accessible :lang
end
推荐答案
add_index :words, ["id", "language_id"], :unique =>真实
它应该可以工作.也许您的数据库中已经有一些非唯一数据并且无法创建索引?但是(正如@Doon 注意到的那样,这将是多余的,因为 id 始终是唯一的).所以你需要在两列上创建主键.
It should work. Maybe you have already some non-unique data in your db and index can't be created? But (as @Doon noticed it will be redundant since id is always unique). So you need create primary key on two columns.
要在 rails 中定义 2 列主键,请使用:
To define 2 column primary key in rails use:
create_table :words, {:id => false} do |t|
t.integer :id
t.integer :language_id
t.string :value
t.timestamps
end
execute "ALTER TABLE words ADD PRIMARY KEY (id,language_id);"
并使用此 gem 在您的模型中设置 primary_key:http://rubygems.org/gems/composite_primary_keys:
And set primary_key in your model with this gem: http://rubygems.org/gems/composite_primary_keys:
class Word < ActiveRecord::Base
self.primary_keys = :id,:language_id
end
这篇关于基于 2 列定义唯一的主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!