質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.31%
Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

Ruby on Rails 7

Ruby on Rails 7は、2021年12月に正式リリースされました。Ruby on Railsのバージョン7であり、フロントエンド開発環境を大幅に刷新。Node.jsを用いない構成がデフォルトになっています。

Q&A

1回答

502閲覧

updateメソッドで更新できないを解決したい。

fdajo

総合スコア13

Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

Ruby on Rails 7

Ruby on Rails 7は、2021年12月に正式リリースされました。Ruby on Railsのバージョン7であり、フロントエンド開発環境を大幅に刷新。Node.jsを用いない構成がデフォルトになっています。

0グッド

0クリップ

投稿2023/06/12 13:40

編集2023/06/12 15:42

実現したいこと

updateメソッドで更新できないを解決したい。

前提

railsえtodoアプリの開発練習しています。
更新機能を実装中にエラーが発生しました。

ストロングパラメーターを使えば更新できるのですが、
インスタンス変数とパラメーターでは更新ができません。

また、ストロングパラメーターを使って
updateメソッド開始直後にbindingpryでデータの中を見てもnilになっています。
(それでも更新はできています)

ちなみにターミナルでは以下のように表示されていますが、
これは「redirect_to "/tasks"」の結果「Completed 302 Found」になっている認識でよろしいでしょうか。(以下コードの一番下にCompleted 302 Foundと記載しています)

Started PATCH "/tasks/8" for ::1 at 2023-06-12 22:15:30 +0900 Processing by TasksController#update as TURBO_STREAM Parameters: {"authenticity_token"=>"[FILTERED]", "task"=>{"title"=>"qqq"}, "commit"=>"更新", "id"=>"8"} Task Load (0.2ms) SELECT "tasks".* FROM "tasks" WHERE "tasks"."id" = ? LIMIT ? [["id", 8], ["LIMIT", 1]] ↳ app/controllers/tasks_controller.rb:25:in `update' TRANSACTION (0.2ms) begin transaction ↳ app/controllers/tasks_controller.rb:30:in `update' Task Update (1.6ms) UPDATE "tasks" SET "title" = ?, "updated_at" = ? WHERE "tasks"."id" = ? [["title", "qqq"], ["updated_at", "2023-06-12 13:15:30.661679"], ["id", 8]] ↳ app/controllers/tasks_controller.rb:30:in `update' TRANSACTION (4.5ms) commit transaction ↳ app/controllers/tasks_controller.rb:30:in `update' Redirected to http://localhost:3000/tasks Completed 302 Found in 40ms (ActiveRecord: 6.6ms | Allocations: 2918)

該当のソースコード

コントローラー(ストロングパラメーター使わない)

ruby

1class TasksController < ApplicationController 2 3 def index 4 @tasks = Task.all 5 end 6 7 def new 8 9 end 10 11 def create 12 Task.create(title:params[:title]) 13 redirect_to "/tasks" 14 end 15 16 def edit 17 @task = Task.find(params[:id]) 18 end 19 20 def update 21 @task = Task.find(params[:id]) 22 @task.update(title: params[:title]) 23 redirect_to "/tasks" 24 end 25 26 def destroy 27 @task = Task.find(params[:id]) 28 @task.destroy 29 redirect_to "/tasks" 30 end 31 32end

コントローラー(ストロングパラメーター使う)

ruby

1class TasksController < ApplicationController 2 3 def index 4 @tasks = Task.all 5 end 6 7 def new 8 9 end 10 11 def create 12 Task.create(title:params[:title]) 13 redirect_to "/tasks" 14 end 15 16 def edit 17 @task = Task.find(params[:id]) 18 end 19 20 def update 21 #bindingpry ここでやると@task確認するとnil 22 @task = Task.find(params[:id]) 23 #bindingpry ここでやると@task確認するとtitle: に値入っているnil 24 @task.update(task_params) 25 redirect_to "/tasks" 26 end 27 28 def destroy 29 @task = Task.find(params[:id]) 30 @task.destroy 31 redirect_to "/tasks" 32 end 33 34private 35 def task_params 36 params.require(:task).permit(:title) 37 end 38 39end

index.html.erb

1<h2>todoapp</h2> 2<%= link_to "CREATE NEW TASK", "tasks/new" %> 3<h2>TASK LIST</h2> 4<% @tasks.each do |task| %> 5 <p>・<%= task.title %> 6 <%= link_to "編集", "/tasks/" + task.id.to_s + "/edit" %></p> 7 <%= button_to "削除", "/tasks/" + task.id.to_s, method: :delete %></p> 8<% end %>

edit.html.erb

1<h2>EDIT TASK</h2> 2<%= form_with model: @task, local: true do |f| %> 3 <p><%= f.text_field :title %></p> 4 <p><%= f.submit "更新" %></p> 5<% end %>

routes.rb

1Rails.application.routes.draw do 2 get "tasks" => "tasks#index" 3 get "tasks/new" => "tasks#new" 4 post "tasks/create" => "tasks#create" 5 get "tasks/:id/edit" => "tasks#edit" 6 patch "tasks/:id" => "tasks#update",as: :task 7 delete "tasks/:id" => "tasks#destroy" 8end

マイグレーションファイル

class CreateTasks < ActiveRecord::Migration[7.0] def change create_table :tasks do |t| t.string :title t.timestamps end end end

試したこと

updateメソッドは基本的にストロングパラメーターを使って更新処理する。とあったのですが、なぜインスタンス変数とパラメーターでは更新ができないのかが、見つけられませんでした。
これはそういうもんとして覚えるのでしょうか。

redirect_to を使用した際は「Completed 302 Found」になり、「Completed 200 OK」にならない認識でしょうか。

よろしくお願いします。

追記
ターミナル

Started PATCH "/tasks/8" for ::1 at 2023-06-13 00:39:54 +0900 Processing by TasksController#update as TURBO_STREAM Parameters: {"authenticity_token"=>"[FILTERED]", "task"=>{"title"=>"dddd"}, "commit"=>"更新", "id"=>"8"} Task Load (0.1ms) SELECT "tasks".* FROM "tasks" WHERE "tasks"."id" = ? LIMIT ? [["id", 8], ["LIMIT", 1]] ↳ app/controllers/tasks_controller.rb:25:in `update' TRANSACTION (0.1ms) begin transaction Started GET "/tasks/8/edit" for ::1 at 2023-06-13 00:40:43 +0900 Processing by TasksController#edit as HTML Parameters: {"id"=>"8"} Task Load (0.1ms) SELECT "tasks".* FROM "tasks" WHERE "tasks"."id" = ? LIMIT ? [["id", 8], ["LIMIT", 1]] ↳ app/controllers/tasks_controller.rb:19:in `edit' Rendering layout layouts/application.html.erb Rendering tasks/edit.html.erb within layouts/application Rendered tasks/edit.html.erb within layouts/application (Duration: 4.7ms | Allocations: 614) Rendered layout layouts/application.html.erb (Duration: 14.3ms | Allocations: 2711) Completed 200 OK in 17ms (Views: 14.9ms | ActiveRecord: 0.1ms | Allocations: 3453) Started PATCH "/tasks/8" for ::1 at 2023-06-13 00:40:47 +0900 Processing by TasksController#update as TURBO_STREAM Parameters: {"authenticity_token"=>"[FILTERED]", "task"=>{"title"=>"qqqq"}, "commit"=>"更新", "id"=>"8"} Task Load (0.1ms) SELECT "tasks".* FROM "tasks" WHERE "tasks"."id" = ? LIMIT ? [["id", 8], ["LIMIT", 1]] ↳ app/controllers/tasks_controller.rb:25:in `update' Redirected to http://localhost:3000/tasks Completed 302 Found in 3ms (ActiveRecord: 0.1ms | Allocations: 1002) Started GET "/tasks" for ::1 at 2023-06-13 00:40:47 +0900 Processing by TasksController#index as TURBO_STREAM Rendering layout layouts/application.html.erb Rendering tasks/index.html.erb within layouts/application Task Load (0.1ms) SELECT "tasks".* FROM "tasks" ↳ app/views/tasks/index.html.erb:6 Rendered tasks/index.html.erb within layouts/application (Duration: 3.4ms | Allocations: 1798) Rendered layout layouts/application.html.erb (Duration: 9.4ms | Allocations: 3904) Completed 200 OK in 11ms (Views: 9.9ms | ActiveRecord: 0.1ms | Allocations: 4178)

補足情報(FW/ツールのバージョンなど)

ruby 3.2.2
Rails 7.0.5

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

maisumakun

2023/06/12 13:58

> インスタンス変数とパラメーターでは更新ができません。 失敗したコードも提示してください。
fdajo

2023/06/12 15:45

ご連絡ありがとうございます。 失敗したコードはコントローラーが「コントローラー(ストロングパラメーター使わない)」になります。 その時のログを追記のところに記載しています。(ターミナルの情報) それ以外のビューやルーティングファイルは一緒のコートです。 Completedと表示されているのですが、トップページへ画面遷移したときに、データが表示されていません。 よろしくお願いします。
guest

回答1

0

なぜインスタンス変数とパラメーターでは更新ができないのかが、見つけられませんでした。

params.require(:task).permit(:title)で取れる値は、params[:title]ではなくparams[:task][:title]で回収できます。

投稿2023/06/12 22:09

maisumakun

総合スコア146543

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.31%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問