初学者です。
シンプルなアプリを作成する課題にとり組んでいます。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
:追記、route.rb
route.rb
1Rails.application.routes.draw do 2 3 resources :tasks 4 root to: 'tasks#index' 5 6end
実装したいのはボタンタイプなのでbutton_toなど試してみたのですが、書き方が間違っているのかエラー画面が表示されてしまいます。以下がbutton_toで編集したものです。
以下、追記
この作業をする前に、編集画面(edit)と、新規作成画面(new)で、updateアクションとcreateアクションを実装できました。
デザインは違いますがとりあえずできました。
これらはform_forメソッドで編集しました。
edit.html.erb
edit.html.erb
1<h1>タスク編集画面</h1> 2 注:登録ボタンを押すとupdateアクションに処理が飛ぶ 3<%= form_for @task do |f| %> 4<div> 5 <%= f.text_field :title %> 6 <%= f.label :title %> 7</div> 8 9<div> 10 <%= f.text_field :content %> 11 <%= f.label :content %> 12</div> 13 14<%= f.submit %> 15 16<% end %>
new.html.erb
new.html.erb
1<h1>新規作成画面</h1> 2注:登録ボタンを押すとcreateアクションに処理が飛ぶ 3<%= form_for @task do |f| %> 4<div> 5 <%= f.text_field :title %> 6 <%= f.label :title %> 7</div> 8 9<div> 10 <%= f.text_field :content %> 11 <%= f.label :content %> 12</div> 13 14<%= f.submit %> 15 16<% end %>
form_for @task、それからsubmitとすることで勝手に削除ボタンができると思っていました。既存のデータをとってくるということでfindでparamsを取得するのだろうな、というのは把握しています。
・・・まだ解説が不十分だと思いますが、全てにおいて勉強不足で言語化できないです、すいません。
今新たに浮かんだのは、なぜform_forで編集ができなかったか、が知りたいです。
![]
(30c09a56eeb4474d43d10d11539796aa.png)
あなたの回答
tips
プレビュー