Rails:用户无法接受好友请求

时间:2016-09-16 03:17:07

标签: ruby-on-rails

我正在制作我的第一个solo rails项目。这是一个Facebook克隆,目前我无法让用户接受朋友请求。如果发布的信息不足以帮助您找到答案,请告诉我。

friend_request_controller.rb

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
    @user = User.find(current_user)
    friend = User.find(params[:id])
    @friend_request = current_user.friend_requests.new(friend_id: friend)

    if @friend_request.save
        redirect_to user_path(current_user)
    end
end

def update
    friend = User.find(params[:id])
    @friend_request = current_user.friend_requests.find(friend_id: friend)
    @friend_request.accept
end
show.html.erb

Hello my my email is <%= @user.email %>
<% if user_signed_in? %>
   <li>
<%= link_to 'Logout', destroy_user_session_path, :method => :delete %></li>

   <li><%= link_to 'All Users', users_path %>     
</li>
<% else %>
<li>
<%= link_to('Login', new_user_session_path)  %>  
</li>
<% end %>
<ul>

<% current_user.friend_requests.each do |request| %>
<h4>You have new friend requests from:</h4>
<li>
  <%= User.find(request.friend_id).email %>
  <%= link_to "Accept",  friend_request_path(friend_id: @friend),method:"put"   %>  
  <%= link_to "Decline", "#" %>
</li>
<% end %>
</ul>

我知道我的link_to帮助器出现了问题

user.rb

class User < ApplicationRecord
has_many :friend_requests, dependent: :destroy
has_many :pending_friends, through: :friend_requests, source: :friend
has_many :friendships, dependent: :destroy
has_many :friends, through: :friendships
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable
 end
friend_request.rb

class FriendRequest < ApplicationRecord
  belongs_to :user
  belongs_to :friend, class_name: 'User'

def accept
  user.friends << friend
  destroy
end

def destroy
end

end

2 个答案:

答案 0 :(得分:1)

执行@araratan在你的frined_request控制器中提到的+,用params [:friend_id]替换params [:id]。

答案 1 :(得分:0)

而不是:

<%= link_to "Accept",  friend_request_path(friend_id: @friend),method:"put"   %>

尝试将@friend更改为request.friend_id

<%= link_to "Accept",  friend_request_path(friend_id: request.friend_id),method:"put"   %>