1

Quick background: I am creating a simple app where user can add another user as friend. A lot taken from this railscast. To do it, I created a Friendship model to keep track of which User I have added.

Here is what I have:

#Friendship.all
[#<Friendship id: 3, user_id: 6, friend_id: 5, created_at: "2017-09-19 ...
#<Friendship id: 13, user_id: 1, friend_id: 2, created_at: "2017-09-22 17:33:47", updated_at: "2017-09-22 17:33:47">, 
#<Friendship id: 14, user_id: 1, friend_id: 2, created_at: "2017-09-22 18:47:52", updated_at: "2017-09-22 18:47:52">]>

Note that I am (user1) currently able to add the same user twice. If you look at the result of Friendship.all, the last two have user_id: 1, friend_id: 2 twice.

In short, I need to make sure my Friendship model don't have two of matching attributes like the above. Being user1, I should not be allowed to add user2 twice. I don't think Rails' uniqueness validation works in this situation.

Is there a Rails' way of preventing duplicates of creating an object with two of the same attributes like shown above?

Iggy
  • 5,129
  • 12
  • 53
  • 87
  • There was another similar post. My solution: `validates_uniqueness_of :user_id, scope: :friend_id` – Iggy Sep 22 '17 at 21:11

0 Answers0