Reputation: 564
i'm trying to build a following action into my apps. To achieve that, I used the most common way, a join table (:followers) to link the users and the posts.
But I'm encountering a little problem of efficience. Because for each of my posts, It's generating a Exists request to see if my user is following the current_post.
So I would like to know if there is a better solution to solve this request in one time ?
My code :
Post/controller :
def index
@my_user = current_user
@posts = @group.posts.order(upd_at: :desc).includes(:user).includes(:followers)
end
Index view :
<% @posts.each do |post|%>
<%- if post.followers.where(user_id: current_user.id).any?%>
<div class="btn btn-default pull-right" style="margin-top:-100px;">
<i class="fa fa-thumbs-up" aria-hidden="true"></i>
</div>
<% else %>
<div class="btn btn-default pull-right" style="margin-top:-100px;">
<i class="fa fa-thumbs-o-up" aria-hidden="true"></i>
</div>
<% end %>
<% end %>
Upvotes: 2
Views: 42
Reputation: 6121
Try checking for include?
..
<%- if post.followers.pluck(:user_id).include?(current_user.id)%>
Upvotes: 2