我正在尝试使用friends_to来接受使用friends_requests控制器中的update方法的好友请求。当我单击链接时,它就像一个没有基本情况的递归方法,我最终得到了“堆栈级到深度”错误。在日志中,我得到了一堆app / models / friendship.rb:11:在`create_inverse_relationship'
编辑#为了我的价值,我正在使用设计进行身份验证。
视图:users / index
<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
答案 0 :(得分:0)
在你的友谊中,你在#create
回调中调用after_create
,这将再次调用回调。根据您的设置,您可以通过确保仅在友谊尚不存在时调用它来阻止这种情况:
def create_inverse_relationship
if friend.friendships.where(friend: user).blank?
friend.friendships.create(friend: user)
end
end