From b862f49a2773a7fd4436b82dbbecd59648952d14 Mon Sep 17 00:00:00 2001 From: Kaio Magalhaes Date: Wed, 13 Mar 2024 12:36:53 -0300 Subject: [PATCH] add uniqueness between user and permission --- app/models/user_permission.rb | 2 ++ spec/models/user_permission_spec.rb | 11 +++++++++++ 2 files changed, 13 insertions(+) diff --git a/app/models/user_permission.rb b/app/models/user_permission.rb index dd2cc4f..f473bc6 100644 --- a/app/models/user_permission.rb +++ b/app/models/user_permission.rb @@ -28,6 +28,8 @@ class UserPermission < ApplicationRecord validates :user, presence: { message: 'must be present' } validates :permission, presence: { message: 'must be present' } + validates :user_id, uniqueness: { scope: :permission_id, message: 'already has this permission' } + def name [user&.email, permission&.name].join(' - ') end diff --git a/spec/models/user_permission_spec.rb b/spec/models/user_permission_spec.rb index 70cb0ae..84b16f3 100644 --- a/spec/models/user_permission_spec.rb +++ b/spec/models/user_permission_spec.rb @@ -27,5 +27,16 @@ describe 'associations' do it { should belong_to(:user) } it { should belong_to(:permission) } + + it 'validates uniqueness of user_id scoped to permission_id' do + permission = create(:permission) + user1 = create(:user) + + user_permission1 = create(:user_permission, user: user1, permission:) + expect(user_permission1).to be_valid + user_permission2 = build(:user_permission, user: user1, permission:) + user_permission2.save + expect(user_permission2).to be_invalid + end end end