LoginSignup
5
4

More than 3 years have passed since last update.

【Ruby】link_toのdestroyアクションが機能しないときの対処法

Posted at

Ruby on RailsでDBのCRUD操作ができるアプリケーションを公式のチュートリアルに沿って作成していたが、削除(destroy)ができない症状が発生したので、その対処法。

結論

link_tobutton_toに変更すると動く。

ただし、デザインが変わる。link_toを使いたかったが、ググっても回答はでてこず。

rails 6以前でも似た症状がでていて、jQueryをオフにするだの、application.jsの一部をコメントアウトするとだのといった解決策が提示されていたが、version 6では該当箇所が存在しない。

confirmも使えない

なお、button_toでは確認ダイアログを表示する、data: {confirm: "アラート内容"}が使えない。

頼むぜrailsさん、、

症状

ルートはリソースフルを使用。

routes.rb
Rails.application.routes.draw do
  resources :articles
end
ルーティングの確認
$ bin/rails routes
      Prefix Verb   URI Pattern                  Controller#Action
        root GET    /                            articles#index
    articles GET    /articles(.:format)          articles#index
 new_article GET    /articles/new(.:format)      articles#new
     article GET    /articles/:id(.:format)      articles#show
             POST   /articles(.:format)          articles#create
edit_article GET    /articles/:id/edit(.:format) articles#edit
             PATCH  /articles/:id(.:format)      articles#update
             DELETE /articles/:id(.:format)      articles#destroy

DELETEメソッドでdestroyアクションが実行されるようになっている。


コントローラのdestroyアクション

articles_controller.rb
  def destroy
    @article = Article.find(params[:id])
    @article.destroy

    redirect_to root_path
  end

  def edit
    @article = Article.find(params[:id])
  end

渡されたパラメータに該当するデータを取得して、destroyメソッドで削除するというシンプルな処理。


ビュー

link_toでdeleteメソッドを指定してdestroyアクションを実行するように指定。

show.html.erb
  <li><%= link_to "Destroy", article_path(@article),
                  method: :delete,
                  data: { confirm: "Are you sure?" } %>

これを実行しても、destroyアクションにとばず、GETメソッドでeditアクションが実行されてしまう、、

解決策

link_tobutton_toに変更

show.html.erb
  <li><%= button_to "Destroy", article_path(@article), method: :delete } %>

確認ダイアログを表示するconfirmが機能しないので削除。



以上。

5
4
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
5
4