Skip to content

Commit

Permalink
add uniqueness between user and permission
Browse files Browse the repository at this point in the history
  • Loading branch information
kaiomagalhaes committed Mar 13, 2024
1 parent 75ba372 commit b862f49
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
2 changes: 2 additions & 0 deletions app/models/user_permission.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions spec/models/user_permission_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit b862f49

Please sign in to comment.