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 3 years have passed since last update.

rails5 progate 整理メモ

Posted at

いいねした投稿の一覧を表示しよう(1)

「いいね!」をした投稿を一覧で表示するために、likesアクションをusersコントローラ内に作成しましょう。

ルーティングを設定

routes.rb
get "users/:id/likes" => "users#likes"

usersコントローラーのlikesアクションを設定

users_controller.rb
.
.
.
  def likes
  end
.
.
.

アクション名と同じhtml名を設定

likes.html.erbを作成する。

いいねした投稿の一覧を表示させるためのリンクを作成する

.
.
.
    <ul class="user-tabs">
      <li class="active"><%= link_to("投稿", "/users/#{@user.id}") %></li>
      <li><%= link_to("いいね!", "/users/#{@user.id}/likes") %></li>
    </ul>
.
.
.

これでlikesアクションを作動させるためのリンクを作成

いいねした投稿の一覧を表示しよう(2)

likesアクションの中身を設定する

インスタンス変数を定義する

users_controller.rb
.
.
.
def likes
    # 変数@userを定義してください
    @user = User.find_by(id: params[:id])
    
    # 変数@likesを定義してください
    @likes = Like.where(user_id: @user.id)
    
  end
.
.
.

一つずつ取り出されたLikeインスタンスのuser_idからPostモデルを取り出す

likes.html.erb

likes.html
.
.
.
    <!-- 変数@likesに対してeach文を用いてください -->
    <% @likes.each do |like| %>
      <!-- 変数postを定義してください -->
      <%= post = Post.find_by(id: like.user_id) %>
    <% end %>
.
.
.

find_byメソッドを用いて、idが「like.post_id」のPostインスタンスを取得してください

likes.html
.
.
.
    <% @likes.each do |like| %>
      <!-- 変数postを定義してください -->
      <% post = Post.find_by(id: like.user_id) %>
    <% end %>
.
.
.
likes.html
.
.
.
   <% @likes.each do |like| %>
      <!-- 変数postを定義してください -->
      <% post = Post.find_by(id: like.user_id) %>
    <% end %>
.
.
.

<% post = Post.find_by(id: like.user_id) %>

なんで<%=をつけなくていいのだろうか?

each文に対応する<% end %>を追加してください

      <% @likes.each do |like| %>
      <!-- 変数postを定義してください -->
        <% post = Post.find_by(id: like.post_id) %>
.
.
.
    <!-- each文のendを追加してください -->
    <% end %>

もっと下に<% end %>に書かなくてはいけなかった。

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?