【问题标题】:Rails HABTM has_many destroy errorRails HABTM has_many 破坏错误
【发布时间】:2017-08-18 00:01:20
【问题描述】:

我有一个has_and_belongs_to_many 在用户和工作区之间使用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.:从“user_workspaces”中删除 "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

我怎样才能涵盖这两种情况?销毁用户会销毁关联和工作区,销毁工作区也会销毁关联

【问题讨论】:

    标签: ruby-on-rails has-many-through has-and-belongs-to-many minitest


    【解决方案1】:

    根据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 函数,但添加dependent: :destroy 以同时销毁关联。

    用户.rb

        before_destroy: :delete_workspaces
        has_many :workspaces,           through: :user_workspaces,                                   
                                         dependent: :destroy
    
     def delete_workspaces
       self.workspaces.each(&:destroy)
     end 
    

    现在两个测试都通过了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-05
      • 1970-01-01
      • 1970-01-01
      • 2012-11-11
      • 1970-01-01
      • 2015-07-04
      • 2010-12-14
      • 1970-01-01
      相关资源
      最近更新 更多