link_to导致"Stack level to deep"



我正在尝试使用Friends_requests Controller中的更新方法来接受link_to来接受朋友请求。当我单击链接时,它的作用就像没有基本情况的递归方法,最终出现了"堆栈级别至深"错误。在日志中,我得到了一堆应用/模型/友谊。

编辑#对于我正在设计用于身份验证的值得的值。

视图:用户/索引

<ul>
  New friend requests
  <% @incoming.each do |user| %>
  <% @users.each do |f| %>
  <% if f.id == user.user_id %>
  <li>
    <%= f.name %>
###### id:1 or  id: user.id both lead to the same error.
    <%= link_to "Accept request", friend_request_path(id: 1), :method => :put %>
  </li>
  <% end %>
  <% end %>
</ul>
<% end %>

friend_requests控制器:

class FriendRequestsController < ApplicationController
    before_action :set_friend_request, except: [:index, :create]
    def index
        @incoming = FriendRequest.where(friend: current_user)
        @outgoing = current_user.friend_requests
    end
    def create
        friend = User.find(params[:friend_id])
        @friend_request = current_user.friend_requests.new(friend: friend)
        if @friend_request.save
            flash[:notice]="Friend request sent."
            redirect_to root_path
        else
            flash[:alert]="Friend request not sent."
            redirect_to root_path
        end
    end
    def update
        @friend_request.accept
        head :no_content
        flash[:notice]="Friend added!"
        redirect_to root_path
    end
    def destroy
        @friend_request.destroy
        head :no_content
    end

    private
    def set_friend_request
        @friend_request = FriendRequest.find(params[:id])
    end
end

用户控制器:

class UsersController < ApplicationController
  def index
    @users = User.all
    @incoming = FriendRequest.where(friend: current_user)
  end
  def show 
    @user = current_user
  end 
end

friend_request模型:

class FriendRequest < ApplicationRecord
    belongs_to :user
    belongs_to :friend, class_name: 'User'
    # This method will build the actual association and destroy the request
    def accept
        user.friends << friend
        destroy
    end
end

友谊模型:

class Friendship < ActiveRecord::Base
  after_create :create_inverse_relationship
  after_destroy :destroy_inverse_relationship
  belongs_to :user
  belongs_to :friend, class_name: 'User'
  private
  def create_inverse_relationship
    friend.friendships.create(friend: user)
  end
  def destroy_inverse_relationship
    friendship = friend.friendships.find_by(friend: user)
    friendship.destroy if friendship
  end
end

在您的友谊中,您正在after_create回调中调用#create,这将再次调用回调。根据您的设置,您可能可以通过确保只有在友谊尚不存在的情况下才能打电话来防止这种情况:

  def create_inverse_relationship
    if friend.friendships.where(friend: user).blank?
      friend.friendships.create(friend: user)
    end
  end

最新更新