0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Rails】destroyで関連するレコードも一緒に削除する方法

Posted at

たとえば、自分の投稿したメッセージを削除する機能を実装しようとした際に、そのメッセージにいいねがついていると、いいねも一緒に削除しないといいねだけが残ってしまい、不具合の原因となってしまいます。

方法

Modelにdependent: :destroyを追記してあげれば、railsがよしなに削除してくれます。

# message.rb
has_many :likes, dependent: :destroy

ちなみに、viewはこのように記述しております。

<%= link_to "削除",{controller: "messages", action: "destroy", message_id: message.id, user_id: current_user.id, score_id: @score.id }, method: :delete, remote: true, data: {confirm: "削除しますか?"} %>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?