diff --git a/app/models/conference.rb b/app/models/conference.rb index 6036a962..048da738 100644 --- a/app/models/conference.rb +++ b/app/models/conference.rb @@ -4,7 +4,8 @@ class Conference < ActiveRecord::Base require 'uri' serialize :events_per_week, Hash # Needed to call 'Conference.with_role' in /models/ability.rb - resourcify + # Dependent destroy will fail as roles#destroy will be cancelled,hence delete_all + resourcify :roles, dependent: :delete_all default_scope { order('start_date DESC') } diff --git a/app/models/role.rb b/app/models/role.rb index 07c5b29e..9673e700 100644 --- a/app/models/role.rb +++ b/app/models/role.rb @@ -1,10 +1,17 @@ class Role < ActiveRecord::Base belongs_to :resource, polymorphic: true has_and_belongs_to_many :users, join_table: :users_roles - + before_destroy :cancel scopify validates :name, presence: true validates :name, uniqueness: { scope: :resource } + + private + + # Needed to ensure that removing all user from role doesn't remove role. + def cancel + false + end end diff --git a/lib/tasks/roles.rake b/lib/tasks/roles.rake new file mode 100644 index 00000000..8c817db0 --- /dev/null +++ b/lib/tasks/roles.rake @@ -0,0 +1,15 @@ +namespace :roles do + desc 'Adds back deleted roles to all conferences' + task add: :environment do + + Conference.all.each do |c| + Role.where(name: 'organizer', resource: c).first_or_create(description: 'For the organizers of the conference (who shall have full access)') + Role.where(name: 'cfp', resource: c).first_or_create(description: 'For the members of the CfP team') + Role.where(name: 'info_desk', resource: c).first_or_create(description: 'For the members of the Info Desk team') + Role.where(name: 'volunteers_coordinator', resource: c).first_or_create(description: 'For the people in charge of volunteers') + end + + puts 'All done!' + end +end + diff --git a/spec/models/role_spec.rb b/spec/models/role_spec.rb index 36cd9a6b..db2b04f9 100644 --- a/spec/models/role_spec.rb +++ b/spec/models/role_spec.rb @@ -5,10 +5,19 @@ describe Role do let!(:organizer_role) { Role.find_by(name: 'organizer', resource: conference) } let!(:cfp_role) { Role.find_by(name: 'cfp', resource: conference) } let!(:organizer) { create(:user, role_ids: organizer_role.id) } + let(:user) { create(:user) } it 'get_users' do expect(organizer_role.users).to include organizer expect(organizer_role.users.count).to eq 1 expect(cfp_role.users).to eq [] end + + it 'does not delete role when last user of role is removed' do + user.add_role :cfp, conference + expect(cfp_role.users).to include user + user.remove_role :cfp, conference + expect(cfp_role.users).to eq [] + expect(conference.roles.count).to eq 4 + end end