我怎樣才能確保:Rails - 如何驗證兩個字段在結合時是唯一的?
一旦我
type: 1 style: 2
我不能添加
type: 2 style: 1
因爲組合應該是唯一的?
心想:
validate :unique_relationship
def unique_relationship
(user_id.to_s + friend_id.to_s).uniq
end
,但不認爲uniq的會工作。
我怎樣才能確保:Rails - 如何驗證兩個字段在結合時是唯一的?
一旦我
type: 1 style: 2
我不能添加
type: 2 style: 1
因爲組合應該是唯一的?
心想:
validate :unique_relationship
def unique_relationship
(user_id.to_s + friend_id.to_s).uniq
end
,但不認爲uniq的會工作。
如何
def unique_relationship?
self.class.where("(user_id = ? and friend_id = ?) or (user_id = ? and friend_id = ?)", user_id, friend_id, friend_id, user_id).empty?
end
如果結果集爲empty?
,:user_id
和:friend_id
之間沒有任何關係存在。
在這種情況下,我絕對會使用數據庫約束,因爲數據庫可以比使用rails更高效。
你要創建一個多列索引
add_index :table, [:column_one, :column_two], unique: true
注意,這意味着創建/更新可能現在拋出異常。如果你期望這是一個罕見的情況,那可能沒關係。如果沒有,你會想做點什麼。