2010-05-13 24 views

回答

7

您可以驗證添加到您的模型,以禁止重複值

class MyModel < ActiveRecord::Base 
    validates_uniqueness_of :my_column_name 
end 
+3

這不會在mysql表級別工作... – ohana 2010-05-13 20:52:53

+0

這個工作對我來說與MySQL版本14.14 DISTRIB 31年5月5日,爲Debian的Linux-GNU(x86_64的)。我喜歡這個解決方案。 – Askar 2013-06-19 07:03:45

+0

對於交通繁忙多個進程,這可能會斷裂。 – lulalala 2013-07-04 07:21:08

-4
counter = 0 
Model.all.each {|m| m.some_value = counter; m.save; counter += 1;} 

:)

,然後添加驗證爲@j。回答

-1

有人糾正我,如果我錯了,因爲我還沒有親自用過,但我相信你可以使用遷移設置唯一在數據庫級別上。

def self.up 
    change_column :<table name>, :<attribute name>, :<data type>, :unique => true 
end 
+0

試過這個,沒有工作。 – ohana 2010-05-13 20:50:32

+0

mysql。之後我這樣做,我添加重複數據到數據庫沒有問題 – ohana 2010-05-14 00:17:50

+0

我相信':unique'關鍵是屬於'只add_index'的選項。 – lulalala 2013-07-04 07:37:19

3

這是代碼直接從我的工作項目:

add_index(:tickets, [:to_email, :body_hash, :from_email] , :unique => true, :limit => 255) 

注意,如果您使用的文本字段唯一的(而不是字符串),雖然它不是」的限制功能時,才需要在軌道上實現(尚未達到3.0我相信)。您可以通過使用插件mysql_index_length http://github.com/eparreno/mysql_index_length/

add_index(:table_name, [:column_name, :second_column_name, :third_column_name] , :unique => true, :limit => 255) 

這個例子是三列創建唯一索引,但如果你希望你可以使用它的一列繞開這一限制。

鏈接到該項目在GitHub上:http://github.com/thinkbohemian/WhySpam/blob/master/db/migrate/20091223193335_add_unique_index.rb

4
class MyModel < ActiveRecord::Base 
    validates_uniqueness_of :my_column_name 
end 

上述建議可能會斷裂,如果你正在運行獨角獸多的Heroku DYNOS,各有多個web程序等

因此更好的辦法這樣做將是

class AddEmailIndexToUser 
    def change 
    # If you already have non-unique index on email, you will need 
    # to remove it before you're able to add the unique index. 
    add_index :users, :email, unique: true 
    end 
end 

https://robots.thoughtbot.com/the-perils-of-uniqueness-validations

,或者您可以使用原始SQL遷移做到這一點。

execute <<-SQL 
    ALTER TABLE Persons 
    ADD UNIQUE (P_Id) 
SQL