I have users and projects resources and join table that connects them called project_members. I wish to have functionality when all users leave the project, the project destroys itself, something like spec below:
75 it 'deletes the project when there are no more users on it' do
76 lambda do
77 project.users.clear
78 end.should change(Project, :count).by(-1)
79 end
So far I came up with this line but don’t know where to put it…
@project.destroy if @project.users.empty?
EDIT: here are my models
User model (I’m using Devise)
1 class User < ActiveRecord::Base
2
3 has_many :synapses #aka project_members
4 has_many :projects, :through => :synapses
5
6 # Include default devise modules. Others available are:
7 # :token_authenticatable, :encryptable, :lockable, :timeoutable and :omniauthable
8 devise :database_authenticatable, :registerable,
9 :recoverable, :rememberable, :trackable, :validatable,
10 :confirmable
11
12 # Setup accessible (or protected) attributes for your model
13 attr_accessible :email, :password, :password_confirmation, :remember_me
14 end
Project model
1 class Project < ActiveRecord::Base
2
3 has_many :synapses
4 has_many :users, :through => :synapses, :dependent => :nullify
5 has_many :tasks, :dependent => :destroy
6
7 #use this when you don't have callbacks
8 #has_many :tasks, :dependent => :delete_all
9
10 validates :name, :presence => true,
11 :uniqueness => true
12 validates :description, :presence => true
13
14 attr_accessible :name, :description
15
16 end
Synapses model AKA (project members)
1 class Synapse < ActiveRecord::Base
2
3 belongs_to :user,
4 :class_name => 'User',
5 :foreign_key => 'user_id'
6 belongs_to :project,
7 :class_name => 'Project',
8 :foreign_key => 'project_id'
9
10 end
Tasks model
1 class Task < ActiveRecord::Base
2
3 belongs_to :project
4 belongs_to :user
5
6 validates :name, :presence => true
7 validates :description, :presence => true,
8 :length => { :minimum => 10 }
9
10 attr_accessible :name, :description
11
12 end
A callback on the membership model should do it: