Follow actions for all instances of object

103 views Asked by At

Currently I have full functionality when displaying the Follow/unfollow button for one user. I'm able to follow and unfollow any user properly.

However, When displaying a list of all users and displaying a Follow/Unfollow button on each.

When I click on follow I get.

I get undefined local variable or method `following' for #<#:0x007fa8a9b4f448> on line two of _unfollow.html.erb - See photo below for full error

I'm passing in the variable when I render the partial.

<%= render 'follow_aud_form', :following => following if signed_in? %> 

I'm also able to inspect "following" and see the instance data.

After clicking when I go back, it actually follow/unfollows the selected user, however it generates the error first

See code below

users_controller

def following
 @title = "Following"
 @user = User.find(params[:id])
 @users = @user.followed_users
 render 'show_follow'
end

def followers
  @title = "Followers"
  @user = User.find(params[:id])
  @users = @user.followers
  render 'show_follow'
end

show_follow.html.erb

<% @users.each do |following|%>

        <div class="span1">
          <%= render 'follow_aud_form', :following => following if signed_in? %>
        </div>

    <% end %>

follow_aud_form

<div id="follow_form">
  <% if current_user.following?(following) %>
    <%= render 'unfollow', :following => following %>
  <% else %>
    <%= render 'follow', :following => following %>
  <% end %>
  </div>

_follow_html

|__<%= @gaza_id = following.id %>__|
<%= form_for(current_user.relationships.build(followed_id: @gaza_id)) do |f| %>
  <div><%= f.hidden_field :followed_id %></div>
  <%= f.submit "Follow",:type => :image, :src => "/assets/follow.png" %>
<% end %>

_unfollow.html

|__<%= @slim_id = following.id %>__|
<%= form_for(current_user.relationships.find_by_followed_id(@slim_id),
             html: { method: :delete }) do |f| %>
  <%#= f.submit "Unfollow", class: "btn btn-large" %>
  <%= f.submit "Unfollow",:type => :image, :src => "/assets/following.png" %>
<% end %>

I've also viewed Users list with follow/unfollow button

enter image description here

1

There are 1 answers

1
Rafael Martinez On

Just try changing the _show_follow.html.erb to:

<% @users.each do |following|%>

    <div class="span1">
      <% f = signed_in? ? following : ''
      <%= render 'follow_aud_form', :following => f %>
    </div>

<% end %>

I believe the only problem you have is that the local var :following is not created unless you the user is signed in. The change proposed just makes sure that the local variable is created anyway.