2013-01-01 39 views

回答

1

如何

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之間沒有任何關係存在。

0

在這種情況下,我絕對會使用數據庫約束,因爲數據庫可以比使用rails更高效。

你要創建一個多列索引

add_index :table, [:column_one, :column_two], unique: true 

注意,這意味着創建/更新可能現在拋出異常。如果你期望這是一個罕見的情況,那可能沒關係。如果沒有,你會想做點什麼。

相關問題