2013-01-01 26 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 

注意,这意味着创建/更新可能现在抛出异常。如果你期望这是一个罕见的情况,那可能没关系。如果没有,你会想做点什么。

相关问题