Todoアプリを作っています。
Categoryモデル(親)とTodoモデル(子)の関係です。
categoryを投稿して、各Categoryのshowアクションのビューでtodoを投稿することができます。
todoはeachで表示させ各todoに削除ボタンをつけてます。
#####起きてる問題
今回、todoの削除機能を実装しているのですが、削除ボタンを押すと削除したいレコードでなく一番古いレコードから削除されてしまいます。
コントローラー側のdestroyアクションにての削除するレコードの指定の仕方が合ってないと思うのですが、わかりません。
ルーティング Rails.application.routes.draw do root 'categories#index' resources :categories, only: [:index, :show, :create, :edit,:update, :destroy] do resources :todos, only: [:create,:edit,:update,:destroy] end end
categoriesコントローラー class CategoriesController < ApplicationController before_action :set_category,only:[:show,:destroy,:edit,:update] def index @categories = Category.all @category = Category.new end def show @todos = @category.todos @todo = Todo.new end def create @category = Category.create(category_params) if @category.save redirect_to root_path else render :index end end def edit end def update @category.update(category_params) if @category.save redirect_to root_path else render :index end end def destroy @category.destroy redirect_to root_path end private def category_params params.require(:category).permit( :name) end def set_category @category = Category.find(params[:id]) end end
todoコントローラー class TodosController < ApplicationController before_action :set_category,only:[:create] def create @todo = Todo.create(todo_params) if @todo.save redirect_to category_path(@category.id) else redirect_to category_path(@category.id) end end def destroy @todo= Todo.find_by(params[:id]) #これだと一番古いレコードから削除されてしまう。 @todo.destroy redirect_to category_path end private def todo_params params.require(:todo).permit( :description,:date).merge(category_id: @category.id) end def set_category @category = Category.find_by(id:params[:category_id]) end end
ビュー cetagories/show.html.haml = form_for [@category,@todo] , html: { class: "category" } do |f| %p Todo = f.text_area :description, placeholder: "Todoタスクを入力してください(150字以内)", type: "text", class: 'category__name' = f.date_field :date, type:"date" = f.submit '作成する', class: 'category__submit' - if @todos.present? - @todos.each do |todo| .category-box .category-box__name = todo.description = todo.date .category-box__edit = link_to '削除', category_todo_path(@category.id,todo.id), method: :delete
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/07/10 04:41
2019/07/10 04:43
2019/07/10 04:54
2019/07/10 05:44
2019/07/10 07:05
2019/07/10 07:20