初学者です。
シンプルなアプリを作成する課題にとり組んでいます。CRUDの機能を実装したいと思っているのですが、その一つであるdestroy(削除機能)の実装の仕方がわからず進めることができずにいます。
今回作成するのはこのようなアプリで、削除機能を実装したいのは、一覧画面(index)と詳細画面(show)です。
以下がお手本とされるものです。
そして以下が私の現在の進捗状況となります。(一覧画面indexのみ。詳細画面showアクションはまだ編集していません)
エディタでは以下のように編集してみました。
index.html.erb
index.html.erb
1 2 3<h1>タスク一覧</h1> 4<ul> 5 6 <% @tasks.each do |task| %> 7 <li> 8 title: <%= task.title %> 9 </li> 10 11 <li> 12 content: <%= task.content %> 13 </li> 14 15 <%= link_to "delete", task, method: :delete, 16 data: { confirm: "You sure?" } %> 17 18 19 20 <% end %> 21 22 23 24</ul>
task_controller.rb
task_controller
1 2class TasksController < ApplicationController 3 def index 4 @tasks = Task.all 5 end 6 7 def new 8 @task = Task.new 9 end 10 11 def edit 12 @task = Task.find(params[:id]) 13 end 14 15 16 def create 17 @task = Task.new(tasks_param) 18 #@task = Task.new(title: params[:task][:title], content: params[:task][:content]) 19 20 if @task.save 21 redirect_to tasks_url 22 else 23 render :new 24 end 25 end 26 27 28 def update 29 30 @task = Task.find(params[:id]) 31 if @task.update(tasks_param) 32 redirect_to tasks_path 33 else 34 render :edit 35 end 36end 37 38 39 def destroy 40 41 @task = Task.find(params[:id]) 42 if @task.destroy(tasks_param) 43 redirect_to tasks_path 44 else 45 render :index 46 47 end 48 end 49 50 private 51 def tasks_param 52 params.require(:task).permit(:title,:content) 53 end 54end
ボタンタイプなのでbutton_toなど試してみたのですが、書き方が間違っているのかエラー画面が表示されてしまいます。
とりあえずlink_toを入れて置いてるような状態です。
コントローラーの書き方が間違っているのか。。。ご教授いただけますでしょうか。
削除機能、ボタンの追加について、です。よろしくお願いいたします。
追記
<%= link_to "delete", task, method: :delete,data: { confirm: "You sure?" } %>
の部分を、
<%= link_to '削除', task_path(@task.id),method: :delete, data: { confirm: "削除してよろしいですか?", commit: "削除する", cancel: "やめる", title: "ご確認ください" } %>
に編集した後のエラー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/12/29 04:10
2018/12/29 04:23
2018/12/31 04:29
2018/12/31 05:07
2019/01/11 08:03