I have a Type has_many Dresses. In the Dress table, I have a column called type_id which references the Type model. What I want to do is whenever a Type object is deleted, all of the associated Dress objects will update their type_id to nil.
So far, I tried this in the console and it works:
> Dress.where(type_id: 3).update_all(type_id: nil)
However, when I translate it in the TypesController like this:
def destroy
type_id = params[:id]
if Type.find(type_id).destroy
Dress.where(:type_id => type_id).update_all(:type_id => nil)
redirect_to admins_path
end
end
…and try it in the browser, the Type object is deleted but the Dress type_id was not updated.
This is the log output:
DELETE FROM "types" WHERE "types"."id" = $1 [["id", 3]]
UPDATE "types" SET position = (position - 1) WHERE (1 = 1 AND position > 2)
COMMIT
UPDATE "dresses" SET "type_id" = NULL WHERE "dresses"."id"
IN (SELECT "dresses"."id" FROM "dresses" WHERE "dresses"."type_id" = 0)
I don’t understand why it sets the type_id = 0 in the last UPDATE command but before that it was set correctly in the DELETE command.
Does not it work?