LoginSignup
0
0

More than 3 years have passed since last update.

ユーザーと投稿の結びつけ「@を使ったlink_toの使い方」

Posted at

<%=link_to(@user.name, "/users/#{@user.id}") %>

・概要説明

 目的:ユーザーの投稿詳細を表示したいのでユーザーと投稿を結びつけたい。
 ポイント:link_toのやり方は様々だが今回はpostsコントローラで定義した@userを使ってのことだったので少しややこしかった。
 

指定のcontroller(僕はcontrollers/posts_controller)

def show   
  @user = User.find_by(id: @post.user_id)
end

解説

User.find_by(id: @post.user_id)のUserはMysquelなどで作ったデータベースのusers。
find_byはその指定した(User)データから入手するものを定義。
@postはデータベースの投稿要素。
userのidとpostのidを結びつけたいので@user = User.find_by(id: @post.user_id)とする。

指定のview(僕はviews/posts/show.html.erb)に

<%= link_to("表示したいもの", "表示したい内容の場所") %>

例えば:
<%=link_to(@user.name, "/users/#{@user.id}") %>

とすればできます。

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