rubysherpas / paranoia

acts_as_paranoid for Rails 5, 6 and 7
Other
2.89k stars 529 forks source link

many to many DELETE instead of update deleted_at #474

Open dfens opened 5 years ago

dfens commented 5 years ago

With this simple example

class Category < ApplicationRecord
  acts_as_paranoid
  has_many :categorizations
  has_many :products, through: :categorizations
end

class Product < ApplicationRecord
  acts_as_paranoid
  has_many :categorizations
  has_many :categories, through: :categorizations
end

class Categorization < ApplicationRecord
  acts_as_paranoid
  belongs_to :product
  belongs_to :category
end

Execution of Product.last.categories = [Category.first] brings DELETE instead of UPDATE.

 Product.last.categories = [Category.first]
  Product Load (0.4ms)  SELECT  "products".* FROM "products" WHERE "products"."deleted_at" IS NULL AND "products"."deleted_at" IS NULL ORDER BY "products"."id" DESC LIMIT ?  [["LIMIT", 1]]
  Category Load (0.5ms)  SELECT  "categories".* FROM "categories" WHERE "categories"."deleted_at" IS NULL AND "categories"."deleted_at" IS NULL ORDER BY "categories"."id" ASC LIMIT ?  [["LIMIT", 1]]
  Category Load (0.3ms)  SELECT "categories".* FROM "categories" INNER JOIN "categorizations" ON "categories"."id" = "categorizations"."category_id" WHERE "categories"."deleted_at" IS NULL AND "categories"."deleted_at" IS NULL AND "categorizations"."deleted_at" IS NULL AND "categorizations"."deleted_at" IS NULL AND "categorizations"."product_id" = ?  [["product_id", 2]]
   (0.1ms)  begin transaction
  Categorization Destroy (0.8ms)  DELETE FROM "categorizations" WHERE "categorizations"."deleted_at" IS NULL AND "categorizations"."deleted_at" IS NULL AND "categorizations"."product_id" = ? AND "categorizations"."category_id" = ? AND "categorizations"."deleted_at" IS NULL  [["product_id", 2], ["category_id", 5]]
  Categorization Create (0.7ms)  INSERT INTO "categorizations" ("product_id", "category_id", "created_at", "updated_at") VALUES (?, ?, ?, ?)  [["product_id", 2], ["category_id", 1], ["created_at", "2019-06-12 18:10:31.931412"], ["updated_at", "2019-06-12 18:10:31.931412"]]
   (3.1ms)  commit transaction

what's the proper way to do it, did I miss something here or is it a flaw in this gem?

duybn-0885 commented 4 years ago

As I see, I think UPDATE = DELETE + INSERT

Able1991 commented 4 years ago

The error is related to the behavior of rails, try this gem https://github.com/cyberxander90/replace_with_destroy or code from it with it, I was made to ensure that all intermediate models with paranoid

lrworth commented 3 years ago

Note this is fixed intrinsically by #442