mercredi 17 août 2016

Following users on Ruby on Rails

I decided to upgrade code of http://ift.tt/1safhxp chapter 14 Following users. My code does not work, when current_user goes on another page and open following. current_user sees himself and want to unfollow like original instagram. unfollow button does not work

show_follow.html.erb
<div class="line-gray-modals"></div>
  <% if @users.any? %>
    <% @users.each do |user| %>
  <ul class="follow-list">
    <li><%= image_tag(user.avatar.url(:thumb), :class => "img-cirkle") %></li>
    <li >
      <div class="modal-follow-ns" > <div class="bold"> <%= link_to user.username, user %></div> <br>
      <div class="modal-follow-ns2"><%= link_to truncate(user.status, :length => 50) %></div></div>
    </li>
    <li class="button-modal">
      <% unless user == current_user %>
        <div id="follow_form">
          <% if current_user.following?(user) %>
            <%= form_for(current_user.relationships.find_by(followed_id: user),
                           html: { method: :delete },
                           remote: true) do |f| %>
              <%= f.submit "Unfollow", class: "btn btn-large" %>
            <% end %>
          <% else %>
            <%= form_for(current_user.relationships.build(followed_id: user.id),
                                                         remote: true) do |f| %>
              <div><%= f.hidden_field :followed_id %></div>
              <%= f.submit "Follow", class: "btn btn-large btn-primary" %>
            <% end %>
          <% end %>
        </div>
      <% end %>
      <% if user == current_user %>
        <%= form_for(@user.relationships.find_by(followed_id: user),
                                          html: { method: :delete },
                                            remote: true) do |f| %>
          <%= f.submit "Unfollow", class: "btn btn-large" %>
        <% end %>
      <% end %>
    </li>
    <%= will_paginate %>
    <li>  <div class="line-gray-modals"></div></li>
  </ul>
<% end %>

relationships_controller.rb

   def create
    @user = User.find(params[:relationship][:followed_id])
    current_user.follow!(@user)
    respond_to do |format|
      format.html { redirect_to @user }
      format.js
    end
  end

  def destroy
    @user = Relationship.find(params[:id]).followed
    current_user.unfollow!(@user)
    respond_to do |format|
      format.html { redirect_to @user }
      format.js
    end
  end

terminal: Completed 500 Internal Server Error in 10ms (ActiveRecord: 1.9ms)

NoMethodError (undefined method `destroy!' for nil:NilClass):

app/models/user.rb:28:in unfollow!' app/controllers/relationships_controller.rb:15:indestroy'

Aucun commentaire:

Enregistrer un commentaire