Add unique index to organization_users table (#358)

* Add unique index to `organization_users` table

- Fix https://github.com/ToolJet/ToolJet/issues/232

* Add respective validation test cases

Co-authored-by: Nishant Samel <nishant@saeloun.com>
This commit is contained in:
Nishant Samel 2021-07-01 12:17:48 +05:30 committed by GitHub
parent 4635db9102
commit 4aa0397f43
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 22 additions and 1 deletions

View file

@ -0,0 +1,5 @@
class AddIndexToOrganizationUsers < ActiveRecord::Migration[6.1]
def change
add_index :organization_users, [:organization_id, :user_id], unique: true, if_not_exists: true
end
end

3
db/schema.rb generated
View file

@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 2021_06_19_124759) do
ActiveRecord::Schema.define(version: 2021_06_30_165919) do
# These are extensions that must be enabled in order to support this database
enable_extension "pgcrypto"
@ -142,6 +142,7 @@ ActiveRecord::Schema.define(version: 2021_06_19_124759) do
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.string "status", default: "invited"
t.index ["organization_id", "user_id"], name: "index_organization_users_on_organization_id_and_user_id", unique: true
t.index ["organization_id"], name: "index_organization_users_on_organization_id"
t.index ["user_id"], name: "index_organization_users_on_user_id"
end

View file

@ -28,6 +28,21 @@ class OrganizationUsersControllerTest < ActionDispatch::IntegrationTest
end
end
test 'org admins cannot create org users if email already exists' do
post '/organization_users', params: org_user_params, as: :json, headers: auth_header(@admin)
post '/organization_users', params: org_user_params, as: :json, headers: auth_header(@admin)
assert_response 422
assert_equal "Email address is already taken", JSON.parse(response.body)['message']
end
test 'OrganizationUser should be unique per organization and user' do
assert_raises(ActiveRecord::RecordNotUnique) do
org_user = OrganizationUser.new(organization: @org, user: @admin, role: 'admin', status: 'active')
org_user.save
end
end
test 'cannot create org users if not admin' do
assert_no_difference 'OrganizationUser.count' do
post '/organization_users', params: org_user_params, as: :json, headers: auth_header(@developer)