如果當前用戶請求了用戶,或者當前用戶已被他們請求,我試圖讓用戶索引中的用戶旁邊出現Pedning Request字樣。我有一種感覺,我的呃,或者我只是完全錯誤的做法。當我點擊添加朋友鏈接時,我希望它重新引導到索引頁面,並且具有更新的請求狀態,但它仍然顯示添加朋友鏈接。Rails:在視圖中顯示待處理的朋友請求
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
你檢查過'friend_requests從'軌道控制檯'表爲了驗證記錄實際上創建正確? – dp7
是的,我知道它正在發送,因爲請求會彈出在其他用戶的頁面上,並閃爍說請求發送彈出的重定向 –