我怎样才能确保: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
注意,这意味着创建/更新可能现在抛出异常。如果你期望这是一个罕见的情况,那可能没关系。如果没有,你会想做点什么。