关注Ruby on Rails上的用户

时间:2016-08-17 10:04:21

标签: ruby-on-rails ruby ruby-on-rails-3

我决定升级https://www.railstutorial.org/book第14章代码跟随用户。当current_user进入另一个页面并打开后面时,我的代码无效。 current_user看到自己,并希望取消关注原始的Instagram。取消关注按钮不起作用

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

终端

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:in `destroy'

1 个答案:

答案 0 :(得分:0)

特别是@user查看下面的代码可能是零。将其更改为user也没有意义。因为你想要取消关注该用户。

 <%= form_for(@user.relationships.find_by(followed_id: user), html: { method: :delete }, remote: true) do |f| %>

相反,请使用current_user

  <%= form_for(current_user.relationships.find_by(followed_id: user), html: { method: :delete }, remote: true) do |f| %>