我有用户和项目资源以及连接它们的连接表,称为 project_members。我希望在所有用户离开项目时具有功能,项目会自行销毁,如下面的规范:
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
到目前为止,我想出了这条线,但不知道放在哪里......
@project.destroy if @project.users.empty?
编辑:这是我的模型
用户模型(我正在使用设计)
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
项目模型
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
突触模型 AKA(项目成员)
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
任务模型
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