2016-09-26 56 views
0

我正在處理我的第一個Rails項目,並遇到一個小問題。我非常感謝任何幫助。 我想顯示使用每個迭代器的當前用戶的所有掛起的朋友請求。我的控制器:Rails:如何顯示所有待處理的朋友請求?

class FriendRequestsController < ApplicationController 
before_action :set_friend_request, except: [:index, :new, :create] 

def index 
    @incoming = FriendRequest.where(friend: current_user) 
    @outgoing = current_user.friend_requests 
end 

def new 
    @friend_request = FriendRequest.new 
end 

def create 
    friend = User.find(params[:friend_id]) 
    @friend_request = current_user.friend_requests.new(friend: friend) 
    if @friend_request.save 
    redirect_back(fallback_location: root_path), status: :created, location: @friend_request 
    else 
    render json: @friend_request.errors, status: :unprocessable_entity 
    end 
end 

當我嘗試像下面一個代碼,它還挺工作,條件語句的工作,因爲它應該,但我知道這是使它工作一個可怕的方式,所以我想使用@incoming自定義。

<% if FriendRequest.where(friend: current_user).present? %> 
    <% ?.each do |request| %> 
     <li><%= ? %></li> 
    <% end %> 
<% else %> 
    You don't have any friend requests 
<% end %> 

但是當我嘗試類似:

<% if @incoming.present? %> 

條件語句不能正常工作,並有「你沒有任何好友請求」,即使當前用戶具有未決好友請求。 我不完全瞭解RoR中的所有工作,所以我會很感激解釋。

+1

嗯,'@ incoming.present?'_should_ work。也許你會犯錯嗎?也可以嘗試'@ incoming.exists?'(這是一個稍微不同的檢查) –

+0

你確定你寫的html代碼位於app/views/friend_requests/index.html.erb裏面嗎? –

+0

@ShabiniRajadas謝謝。這是問題所在,我試圖在導航欄下拉菜單中執行此操作(我應該在後面提到的內容),在您的建議之後,我在app/views/friend_requests/index.html.erb中使用了max代碼,並且它可以正常工作。有沒有什麼辦法讓它在我的導航欄中工作? –

回答

0

讓我們開始爲傳入的朋友請求創建一個特定的關聯。

class User < ActiveRecord::Base 
    # ... 
    has_many :incoming_friend_requests, 
    class_name: 'FriendRequest', 
    source: :friend 
end 

由於Rails無法從關聯的名稱中派生出適當的列,我們指定class_namesource告訴Rails FriendRequest上的哪些關聯是相反的。

當你開始考慮急切的加載和性能時,這是非常重要的。

例如,它可以讓你做的事:

@user = User.joins(:friend_requests, :incoming_friend_requests) 
      .find(params[:id]) 

所以,讓我們使用新的關係:

def index 
    @incoming = current_user.incoming_friend_requests 
    @outgoing = current_user.friend_requests 
end 

要測試是否有一個範圍或集合使用.any?任何項目。 .any?非常聰明,因爲如果關聯已經加載,它不會發出查詢。

<% if @incoming.any? %> 
    <ul> 
    <% @incoming.each do |fr| %> 
    <li><%= fr.name %></li> 
    <% end %> 
    </ul> 
<% else %> 
    <p>You don't have any friend requests</p> 
<% end %> 
+0

'present?'在檢查param鍵,實例變量等的存在時更有用。 – max

+0

非常感謝你這麼長的回答,我全力推遲並試圖在navbar下拉菜單中使用代碼,我應該在我的問題中提到過,但我不知道它是相關的。即使不改變我的模型中的任何內容,我的代碼在app/views/friend_requests/index.html.erb中也能正常工作。 –

1
<% if (frs = FriendRequest.where(friend: current_user)).present? %> 
    <% frs.each do |fr| %> 
     <li><%= fr.name %></li> 
    <% end %> 
<% else %> 
    You don't have any friend requests 
<% end %> 
+3

將數據庫查詢放入視圖是不好的做法。獲取正確的數據不是關注的問題。 –

+0

回答問題是我所關心的。戴夫托馬斯經常評論邏輯的觀點,雖然它可以失去控制,但他建議一種實用的方法,恕我直言,比在你的控制器(或助手)中爲非平凡的視圖設置了許多實例變量更好...但是我離題了..然而讚賞反對.. –

+0

重點是,實例var _應該有工作。還有其他的事情比我們在這裏看到的還要糟糕。你的解決方案只是掩蓋問題,而不是解決問題。 –

相關問題