0
votes

I have a has_and_belongs_to_many using has_many between users and workspaces.

user.rb

class User < ActiveRecord::Base
  has_many :user_workspaces, dependent: :destroy
  has_many :workspaces, through: :user_workspaces 
  before_destroy :delete_workspaces

 def delete_workspaces
   self.workspaces.each(&:destroy)
 end 

workspace.rb

class Workspace < ActiveRecord::Base
  has_many    :user_workspaces
  has_many    :users, through :user_workspaces
end

user_workspaces class and migration:

class UserWorkspace < ActiveRecord::Base 
  self.table_name  = "user_workspaces"
  belongs_to  :user 
  belongs_to  :workspace
end

class CreateUsersAndWorkspaces < ActiveRecord::Migration
  def change
    create_table :users_workspaces, id: false do |t|
      t.belongs_to :user, index: true
      t.belongs_to :workspace, index: true
      t.boolean :admin, default: true  
    end
  end
end
    class RenameUsersWorkspaces < ActiveRecord::Migration
  def change
    rename_table('users_workspaces', 'user_workspaces')
  end
end

I want this both test to pass:

should "destroy all associatios and objects" do 
  user = User.create!(attributes_for(:user))
  w = user.workspaces.create!(attributes_for(:workspace))
  user.destroy 
  assert UserWorkspace.all.empty? #asser there are no associations
end 

which gives me the error

ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: user_workspaces.: DELETE FROM "user_workspaces" WHERE "user_workspaces"."" = ?

 should "destroy association when destroying workspace" do
      user = User.create!(attributes_for(:user))
      w = user.workspaces.create!(attributes_for(:workspace))
      w.destroy
      assert UserWorkspace.all.empty?
 end

How can I cover both scenarios? destroying an user destroys the association and the workspaces, destroying the workspace also destroys the association

1

1 Answers

0
votes

According to http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html just need to ignore the join table.

Workspace.rb now has dependent destroy, to destroy only the join (intended behavior of destroy)

  has_many    :users,             through:      :user_workspaces,
                                  inverse_of:   :workspaces,
                                  dependent:    :destroy

then user.rb keeps the delete_workspaces functions, but adds dependent: :destroy, to also destroy the association.

user.rb

    before_destroy: :delete_workspaces
    has_many :workspaces,           through: :user_workspaces,                                   
                                     dependent: :destroy

 def delete_workspaces
   self.workspaces.each(&:destroy)
 end 

now both test passes.