Has and Belongs to Many Don't Delete or Nullify Join Table Entries

时间:2016-10-20 19:41:48

标签: ruby-on-rails

Is it possible to not delete/destroy a has_and_belongs_to_many association when the record is deleted? I've tried setting dependent: to false, nil, or random values (all still cause the delete statement to be executed) For example:

class User < ActiveRecord::Base
   has_and_belongs_to_many :tags
end

user.destroy
# DELETE FROM "tags_users" WHERE "tags_users"."user_id" = ... (don't want this)
# DELETE FROM "users" WHERE "users"."id" = ... (do want this)

2 个答案:

答案 0 :(得分:0)

The association of a habtm is stored in a join table, keeping those entries would make any sense at all (execpt for some statistics of course), thus rails will always delete them.

Personally I use paranoia in all my models, that should keep your tags_users around for longer, is acts_as_paranoid an option for you?

答案 1 :(得分:0)

由于Rails内部的一些恼人行为,似乎很难禁用has的级联删除并且属于许多关联(参见https://github.com/rails/rails/blob/master/activerecord/lib/active_record/associations.rb#L1811-L1819)。 has_many - through不是这种情况,因此切换到DELETE查询会删除它们(它们是等效的)。

class TagUser
  self.table_name = "tags_users"
  belongs_to :tag
  belongs_to :user
end

class User
  has_many :tag_users
  has_many :tags, through: :tag_users
end

user.destroy
# DELETE FROM "users" WHERE "users"."id" = ...