0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Error】link_toブロックという概念

0
Last updated at Posted at 2024-10-24

今回はlink_toを使用していてエラーが起こったのでどのようなエラーで解決までの内容について記事にまとめておきたいと思います。

環境

  • Windows, WSL
  • Docker
  • Ruby 3.2.3
  • Rails 7.1.3

エラーが発生したコード

<%= link_to "削除", post_path(@post), id: "button-delete-#{@post.id}", data: { turbo_method: :delete, turbo_confirm: "削除しますか?" }, class: "bg-red-500 hover:bg-red-700 text-white font-bold py-3 px-6 rounded text-lg" do %>
<% end %>

👆がエラーが発生したコードになります。
何がいけないのかぱっと見、気づくことができなかった私:sweat:

エラー画面には次のようなことが記載されていました

NoMethodError in Posts#show
Showing /myapp/app/views/posts/show.html.erb where line #40 raised:
undefined method stringify_keys' for "/posts/1":String

原因

改めて、私が入力していたコードを見直すと次のようなことが原因であるとわかりました。

  • link_to ヘルパーの使い方が問題
  • link_to ヘルパーを do ブロック付きで使用する場合、リンクの中身をブロック内に書く必要があるがブロック構文とテキストを同時に使おうとしている(Railsではサポートされていない)
  • link_to に最初の引数 "削除" を渡しているため、do ブロックは使えない。
  • do ブロックを使う場合、テキストやアイコンはブロック内に書く必要がある

解決策

1.ブロックなしで書く場合(シンプルな方法)

<%= link_to "削除", post_path(@post), id: "button-delete-#{@post.id}", data: { turbo_method: :delete, turbo_confirm: "削除しますか?" }, class: "bg-red-500 hover:bg-red-700 text-white font-bold py-3 px-6 rounded text-lg" %>

"削除" というテキストがボタンに表示され、削除処理が実行される

2:ブロックを使う場合(テキストやアイコンを追加したい場合)

<%= link_to post_path(@post), id: "button-delete-#{@post.id}", data: { turbo_method: :delete, turbo_confirm: "削除しますか?" }, class: "bg-red-500 hover:bg-red-700 text-white font-bold py-3 px-6 rounded text-lg" do %>
  削除
<% end %>

do ... end の中に "削除" というテキストが入るため、エラーは発生しない。

さいごにまとめ

今回は削除ボタンに後からアイコンを追加したいので2番目でコードの修正を行いました。
アイコンを後から追加したい時は2番。テキストだけの時はブロックなしでの入力。
基本的なことはエラーが起こって改めて気づき。
今回の記事が何か参考になれば幸いです。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?