0

我有一個has_and_belongs_to_many在用戶和工作區之間使用has_manyRails HABTM has_many破壞錯誤

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 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 

我想這兩個測試通過:

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 

它給我的錯誤

的ActiveRecord :: StatementInvalid:SQLite3的::的SQLException:沒有這樣的列: 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 

我怎麼能涵蓋方案是什麼?破壞用戶銷燬關聯和工作區,破壞工作區也破壞關聯

回答

0

根據http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html只需要忽略連接表。

Workspace.rb現在已經依賴破壞,毀滅只聯接(破壞預期的行爲)

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

然後user.rb保持delete_workspaces功能,但增加了相關的:破壞,也破壞了這個聯繫。

user.rb

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

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

現在兩個測試通過。