LoginSignup
1
1

More than 5 years have passed since last update.

post/showから,postを投稿したuserへいきたい時のpathの指定

Posted at

postのshowページから,そのpostを投稿したuserへいきたい時のpathの指定の仕方をしょっちゅう忘れるため、備忘録。

以下のようなpost/showページがあったとして、

post/show.html.erb

<h1>post詳細</h1>
<p><%= @post.title %>
<p><%= @post.content %>
<p><%= @post.created_at %>
-------------------------
<p><%= link_to @post.user.name,user_path(@listing.user) %> <-ここ

link_toの第一引数で、@postに紐付くuserのname(@post.user.name)を指定。
第二引数では、user_pathただし、@postに紐付くuserへ(@post.user)という指定の仕方。
rails routesでpathを確認すると、

qiita.rb
user GET    /users/:id(.:format)     users#show

のようになっていて、/users/:id(.:format)だから、user_path(@user)でいいのかな、と注意しないと勘違いしやすい(俺は)。
よく考えると、「@userだけじゃ指定できないじゃん!」ってなって当たり前なんだよね

リンクで行きたいのは,「このpostに紐付くuser」なんだから、user_path(@post.user)に決まってるよね〜〜〜

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