Peter Tretiakov
Peter Tretiakov

Reputation: 3410

Undefined local variable or method friendship

I'm trying to add some social functionality to my app, and following RailsCast #163 about self-referential association, but I have a problem with deleting friendship.

On user#show page I have 2 columns: with @users and @friends. The show method from UsersController is:

def show
  @user = User.find(params[:id])
  @users = User.all
  @friends = @user.friends
end

Also I'm using <%= render @users %> and <%= render @friends %> partials, both of them renders _user.html.erb from users folder, which is the following:

<tr>
  <td>
    <%= gravatar_for user, size: 30 %>
  </td>
  <td>
    <%= user.name %>
  </td>
  <td>
    <% if current_user.friends.exists?(user) %>
        <%= link_to 'Remove friend', friendship, :method => :delete %>
    <% else %>
        <%= link_to 'Add friend', friendships_path(:friend_id => user), method: :post %>
    <% end %>
  </td>
</tr>

Everything is ok with models and controllers, as I've checked everything a hundred times. But when I try to open a page I receive an error undefined local variable or method friendship from this line <%= link_to 'Remove friend', friendship, :method => :delete %>.

Upvotes: 0

Views: 445

Answers (3)

jgybrooklyn
jgybrooklyn

Reputation: 1

if you have an instance variable defined in your controller (@friendship or @user) use that opposed to user or friendship for the route.

<%= link_to 'Remove friend', @user, :method => :delete %>

Upvotes: 0

Peter Tretiakov
Peter Tretiakov

Reputation: 3410

It looks awful, but seems that current_user.friendships.find_all_by_friend_id(user.id).first instead of friendship solved my problem. But I'm sure that there is more simple solution.

Upvotes: 0

cortex
cortex

Reputation: 5226

Like the error says, friendship is not defined. You need to pass instead of friendship, the user you want to delete. For example:

<%= link_to 'Remove friend', user, :method => :delete %>

or

<%= link_to 'Remove friend', friendship_path(user), :method => :delete %>

Hope this helps!

Upvotes: 1

Related Questions