I want to display avatars and user names in Posts # index (hereinafter referred to as timeline)
Introducing devise Introduced Active Storage Add avatar to users model
Added has_one_attached
and user instance methods for: avatar
to the posts model
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
Add .user to view
Ruby: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 %>
User model can be handled even in posts # index where params cannot be used by user method.
⇒ You can handle : avatar
linked to the User model by post.user.avatar
Recommended Posts