LoginSignup
1
0

More than 3 years have passed since last update.

Rails 最近の投稿を取得

Posted at

概要

Railsの基本的な投稿アプリで、postした詳細ページにそのユーザーの最近の投稿が一緒に表示されているというアプリをよく見かけます。

その際のデータ取得の方法を残しておきます。
 
Screenshot from Gyazo

コード

私はこのコードでデータを取得しました。


@recent_posts = Post.where(user_id: @post.user_id).order(created_at: :desc).limit(4)

しかし、これだと取得したデータとshowページのデータが同じという事が起こるので
view側で


    <% @recent_posts.each do |post| %>
      <% unless post.id == @post.id %> #この行を追加
        <%= link_to post_path(post) do %>
          <%= image_tag post.image %>
          <p><%= post.name %></p>
        <% end %>
        <p><%= post.updated_at.strftime("%Y/%m/%d")%></p>
      <% end %>
    <% end %>

eachする時にunless文でshowページのpost.idと異なるものだけ表示するようにしました!

以上です。

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