This is probably a silly question, but I want to make sure I understand how the "scope" field with the uniqueness model constraint.
I was following along this guide: https://dankim.io/mutual-friendship-rails/ to understand handling "Friends" associations in rails. At one part it talks about making a uniqueness constraint:
validates :friend, presence: true, uniqueness: { scope: :user } (Which goes in the friendship model.
So this is saying that the friend_id field should never be duplicated with the same user_id field right?
Wouldn't this have also worked as:
validates :user, presence: true, uniqueness: { scope: :friend }
Saying a user shouldn't show up more than once with the user_id having a duplicated friend_id. Or am I mis-understanding how the scope works here?
Thanks!
You are right. Scope is a fancy way of say allow just one duple (user, friend).
If you set an index on your DB (which is necessary to avoid race conditions with uniqueness validation) you'll do exactly the same thing:
add_index :friendships, [:user_id, :friend_id], unique: true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With