0

ユーザーとプロジェクトのリソースがあり、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?

編集:ここに私のモデルがあります

ユーザーモデル(私は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

プロジェクトモデル

  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
4

2 に答える 2

1

メンバーシップ モデルのコールバックがそれを行う必要があります。

class ProjectMember < ActiveRecord::Base
  after_destroy :remove_project_if_last_member
  private
    def remove_project_if_last_member
      project.destroy if project.users.empty?
    end
end
于 2012-05-07T21:48:46.857 に答える