When deleting a model with a foreign key in Rails, I had a hard time implementing it by simply writing the routing, controller and view file, so I will output it.
Suppose you want to delete a model called item that has item_purchase that links data about product purchases as a foreign key.
This item_purchase has a user_id who is the purchaser and an item_id which is the purchased item.
Here, if you simply delete the item, there will be a record in item_purchase where only item_id is missing.
Therefore, when deleting an item, we will describe it so that the related item_purchase record itself can be deleted.
First, let's add an additional description to the model association.
models/item.rb
has_one :item_purchase, foreign_key: :item_id, dependent: :destroy
models/item_purchase.rb
belongs_to :item, optional: true
I won't introduce it here, but since the user should also be linked, don't forget to describe that as well.
After that, you can define the destroy method in the controller as usual.
Recommended Posts