Michael Durrant
Michael Durrant

Reputation: 96604

Rails - how to validate two fields are unique when combined?

How can I make sure that:

once I have

type: 1 style: 2

I can't add

type: 2 style: 1

because the combo should be unique?

I thought:

validate :unique_relationship

def unique_relationship
  (user_id.to_s + friend_id.to_s).uniq
end

but don't think the uniq would work.

Upvotes: 1

Views: 166

Answers (2)

heartpunk
heartpunk

Reputation: 2275

I would absolutely use a database constraint in this case, because the database can do this much more efficiently than you can in rails.

You'll want to create a multi column index

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

Note, this means that creation/update might throw exceptions now. If you expect that to be a rare case, that's probably okay. If not, you'll want to do something about that.

Upvotes: 0

deefour
deefour

Reputation: 35370

How about

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

If the result set is empty?, no relationship between :user_id and :friend_id exists.

Upvotes: 1

Related Questions