1

我怎样才能确保:

一旦我有

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 会起作用。

4

2 回答 2

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

于 2013-01-01T01:11:04.183 回答
0

在这种情况下,我绝对会使用数据库约束,因为数据库可以比在 Rails 中更有效地执行此操作。

您需要创建一个多列索引

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

请注意,这意味着创建/更新现在可能会引发异常。如果您认为这是一种罕见的情况,那可能没问题。如果没有,你会想做点什么。

于 2013-01-01T01:12:58.883 回答