LoginSignup
2
0

More than 3 years have passed since last update.

[Rails] ActiveStorageを使ってpostsにアバターを表示

Last updated at Posted at 2020-10-17

やりたいこと

Posts#index(以下タイムライン)にアバターやユーザー名を表示したい

前提

devise導入
ActiveStorage導入
アバターをusersモデルに追加

やり方

postsモデルに:avatarhas_one_attachedとuserインスタンスメソッドを追加

post.rb
class Post < ApplicationRecord
  validates :content, {presence: true, length: {maximum: 140}}
  validates :user_id, {presence: true}

  has_one_attached :avatar

  def user
    return User.find_by(id: self.user_id)
  end
end

viewに.userを追加

index.html.erb
    <% @posts.each do |post| %>
    <div class="posts-index-item mb-20">
      <div class="posts-index-user">
        <!--avatar-->
        <div class="posts-index-img d-inline">
          <% if post.user.avatar.attached? %>
            <%= image_tag post.user.avatar, class: "avatar-index rounded-circle mx-auto" %>
          <% else %>
            <img class="avatar-index rounded-circle mx-auto" src="<%= "/images/default_user.png" %>" alt="Userimage">
          <% end %>
        </div>
        <!--username-->
        <div class="posts-index-username d-inline">
          <%= link_to post.user.username, users_show_path %>
        </div>
      </div>
      <!--content-->
      <%= link_to(post.content, "/posts/#{post.id}") %>
    </div>
  <% end %>

結果

image.png

まとめ

userメソッドによってparamsの使えないposts#indexでもUserモデルを扱える。
post.user.avatarによりUserモデルに紐づいた:avatarを取り扱える

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