LoginSignup
1
0

More than 1 year has passed since last update.

link_toにclassを付けるのにハマった話とその対処法

Posted at

やりたかったこと

・aタグにclassを設けて、flexboxを使う。

前提

・Ruby 3.0.2
・rails 6.1.4.4
・Bootstrap、slim導入済み
※htmlはslimで記述しています。erbの方は、適宜erbに読み替えてください。
今回、controllerとactionを指定して、リンク先を設定してます。

先に結論

以下のように記述することで解決できました!

= link_to({ controller: 'messages', action: 'roomshow', to_user_id: message_user_id }, class: "d-flex flex-row") do

失敗したパターン

1. classを普通に追記する
= link_to controller: 'messages', action: 'roomshow', to_user_id: message_user_id, class: "d-flex flex-row" do
生成されるHTML
<a href="/users/1/messages/room/2?class=d-flex+flex-row"></a>

この場合、設定したclassがURLに含まれてしまい、classが設定できていません。
※なぜかリンク先には正しく遷移します。。。

2. controllerとaction部をハッシュ({})で囲う

link_toについて調査したところ、リンク先のルーティングについてコントローラーとアクションを指定している場合、ハッシュを使っているパターンを発見したので、それを試してみることに。

= link_to({ controller: 'messages', action: 'roomshow' }, to_user_id: message_user_id, class: "d-flex flex-row" ) do

このパターンは、ActionController::UrlGenerationErrorが発生します。

3. class部もハッシュ({})で囲う
= link_to({ controller: 'messages', action: 'roomshow' }, to_user_id: message_user_id, { class: "d-flex flex-row" } ) do

このパターンは、ActionView::SyntaxErrorInTemplateが発生します。

成功したパターン

= link_to({ controller: 'messages', action: 'roomshow', to_user_id: message_user_id }, class: "d-flex flex-row") do

成功したパターンは、上記の結論の繰り返しになりますが、この書き方です。
URLに関係する箇所すべてをハッシュで囲み、URL部とそれ以外を分ける必要があるようです。
パターン2,3では、to_user_idを囲み忘れていたことが原因でした。

以上、参考になれば幸いです!

参考

https://teratail.com/questions/64203

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