1

I'm unable to check if the current_user is blocking the target user. I'm trying to create a toggle button for the block/unblock feature. I don't know how people were able to do it, unless their solution wasn't AJAX ready. How can I check if the current_user is following the target @user object?

_block_user.html.erb

<% # unless @user == current_user %>
  <% **if current_user.blocking?(@user)** %>
    <%= link_to(unblock_user_path(@user), :remote => true, :class => 'btn btn-outline-danger') do %>
      <i class="fa fa-stop-circle"></i>
      Unblock
    <% end %>
  <% else %>
    <%= link_to(block_user_path(@user) ,:remote => true, :class => 'btn btn-outline-primary') do %>
      <i class="fa fa-play-circle"></i>
      Block
    <%end%>
  <% end %>
<% # end %>
Johnny C
  • 121
  • 1
  • 1
  • 11

2 Answers2

1

If it's a button with AJAX you have to have something like that

<% if (!current_user.liked? @user) %>

        <%= link_to like_user_path(@user), class:"like-btn", method: :put, remote: true do %> 
        <i class="fa fa-stop-circle"></i>
        <% end %>  

    <% else %>

        <%= link_to like_user_path(@user), class:"like-btn", method: :put, remote: true do %> 
        <i class="fa fa-play-circle"></i>
        <% end %> 

 <% end %>

like.js.erb

<% if current_user.liked? @user %>
     document.getElementsByClassName('like-btn')[0].className = "like-btn liked";
<% else %>
     document.getElementsByClassName('like-btn')[0].className = "like-btn disliked";
<% end %>

controller/user

def like
    if !current_user.liked? @user
      @user.liked_by current_user
    elsif current_user.liked? user
      @user.unliked_by current_user 
    end
    respond_to do |format|
        format.html { redirect_back(fallback_location: root_path) }
        format.js 
        end
  end 
Clyde T
  • 141
  • 10
  • Looks good. I used a different approach to get the button showing the correct state. I'll post the solution. – Johnny C Jun 21 '18 at 22:31
0

My approach to finding out if a user is blocked. (tested without the current_user checker)

<% #unless @user == current_user %>
<div id="block_user<%= @user.id %>">
  <% if current_user.blocks.include?(@user) %>
    <%= link_to(unblock_user_path(@user), :remote => true, :class => 'btn btn-outline-danger') do %>
      <i class="fa fa-stop-circle"></i>
      Unblock
    <% end %>
  <% else %>
    <%= link_to(block_user_path(@user), :remote => true, :class => 'btn btn-outline-primary') do %>
      <i class="fa fa-play-circle"></i>
      Block
    <% end %>
  <% end %>
</div>
<% # end %>
Johnny C
  • 121
  • 1
  • 1
  • 11