Rails:在视图中显示待处理的好友请求

时间:2016-09-18 16:08:59

标签: ruby-on-rails

如果当前用户已请求用户索引,或者当前用户已被他们请求,我试图在用户索引中的用户旁边显示“打磨请求”字样。我有一种感觉,我的erb正在扭曲,或者我只是完全采取了错误的方法。当我单击添加好友链接时,我希望它重定向回索引页面,其中包含请求的更新状态,但它仍然显示添加好友链接。

index.html.erb

Facebook Users:
<ul><% @users.each do |user| %>

    <% if current_user == user || current_user.friends.include?(user) %>
        <li><%= link_to user.email, user_path(user) %></li>
<% current_user.friend_requests.each do |request| %>
    <% if request.friend_id == user.id  %>
    <li><%= link_to user.email, user_path(user) %> 
        | Pending Request</li> 
        <% end %>
        <% end %>
    <% else %>
        <li><%= link_to user.email, user_path(user) %> |
        <%= link_to "Add Friend", friend_requests_path(friend_id: user.id), method: :post %>
        </li>   
    <% end %>
 <% end %>
 </ul>

 <%= link_to 'Back to your profile', user_path(current_user) %>


<%= render 'shared/error_messages', object: current_user %>

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

    if @friend_request.save
        flash[:notice] = "Friend request sent!"
        redirect_to users_path
    else
        flash[:notice] = "Unable to request friend"
        redirect_to users_path
    end
end

def update
    friend_email = User.find(@friend_request.friend_id).email

    @friend_request = FriendRequest.find_by_user_id_and_friend_id(params[:friend_id], params[:id])
    if @friend_request.accept
        flash[:notice] = "You and #{friend_email} are now friends!"
        redirect_to user_path(current_user)
    end

end

def destroy
    if @friend_request.destroy
        flash[:notice] = "Request Declined"
        redirect_to user_path(current_user)
    end
end


private

def set_friend_request
    @friend_request = FriendRequest.find_by_user_id_and_friend_id(params[:friend_id], params[:id])
end
end

1 个答案:

答案 0 :(得分:1)

{... 1}}块以...开头

if

...位于以'...开头的'if'块中

<% if request.friend_id == user.id  %>

所以基本上只有当用户是你自己(当前用户)或者用户已经是你的朋友时,才能显示“待处理请求”。当然,这没有任何意义。

最好在第一个<% if current_user == user || current_user.friends.include?(user) %> if之后移动代码,而您实际上并不需要使用else遍历所有请求,只需映射{{1} }的

each