Enterprise roles must be unique

This commit is contained in:
Rohan Mitchell
2014-08-15 15:46:54 +10:00
parent 6e17f0aaa2
commit 95a0bf39f7
4 changed files with 30 additions and 1 deletions

View File

@@ -2,5 +2,8 @@ class EnterpriseRole < ActiveRecord::Base
belongs_to :user, :class_name => Spree.user_class
belongs_to :enterprise
validates_presence_of :user_id, :enterprise_id
validates_uniqueness_of :enterprise_id, scope: :user_id, message: "^That role is already present."
scope :by_user_email, joins(:user).order('spree_users.email ASC')
end

View File

@@ -0,0 +1,8 @@
class AddUniqueAndFkConstraintsToEnterpriseRoles < ActiveRecord::Migration
def change
add_index :enterprise_roles, [:user_id, :enterprise_id], unique: true
add_foreign_key :enterprise_roles, :spree_users, column: :user_id
add_foreign_key :enterprise_roles, :enterprises, column: :enterprise_id
end
end

View File

@@ -11,7 +11,7 @@
#
# It's strongly recommended to check this file into your version control system.
ActiveRecord::Schema.define(:version => 20140723023713) do
ActiveRecord::Schema.define(:version => 20140815053659) do
create_table "adjustment_metadata", :force => true do |t|
t.integer "adjustment_id"
@@ -222,6 +222,7 @@ ActiveRecord::Schema.define(:version => 20140723023713) do
end
add_index "enterprise_roles", ["enterprise_id"], :name => "index_enterprise_roles_on_enterprise_id"
add_index "enterprise_roles", ["user_id", "enterprise_id"], :name => "index_enterprise_roles_on_user_id_and_enterprise_id", :unique => true
add_index "enterprise_roles", ["user_id"], :name => "index_enterprise_roles_on_user_id"
create_table "enterprises", :force => true do |t|

View File

@@ -45,6 +45,23 @@ feature %q{
page.should have_relationship u, e
EnterpriseRole.where(user_id: u, enterprise_id: e).should be_present
end
scenario "attempting to create a relationship with invalid data" do
u = create(:user, email: 'u@example.com')
e = create(:enterprise, name: 'One')
create(:enterprise_role, user: u, enterprise: e)
expect do
# When I attempt to create a duplicate relationship
visit admin_enterprise_roles_path
select 'u@example.com', from: 'enterprise_role_user_id'
select 'One', from: 'enterprise_role_enterprise_id'
click_button 'Create'
# Then I should see an error message
page.should have_content "That role is already present."
end.to change(EnterpriseRole, :count).by(0)
end
end