2016-08-22 95 views
0

我正在嘗試創建一個「我的文件」頁面,其中列出了用戶上傳的文檔,但無法過濾每個用戶的文檔。設計列表用戶文檔

現在它顯示上傳的所有文檔,而不是與上傳文檔的用戶關聯的文檔。

我使用的設計,因爲我一直試圖改變用戶

if語句,以各種不同的條件,但似乎無法過濾與每個用戶相關的文件。

這是我對「我的文件」頁面代碼:

<% @documents.each do |document| %> 
    <% if @document = current_user.documents.find_by(params[:user_id]) %> 
     <%= link_to document.title, document %>: <%= link_to "Download", document.pdf(:original, false) %> 
    <% end %> 
<% end %> 

這是我對myfiles的頁面文件控制器代碼:

def myfiles 
    @documents = Document.all 
end 

有一個簡單的方法,我可以過濾與每個用戶關聯的文檔?

回答

0

此方法將顯示出與只當前用戶相關聯的文檔。

Controller文件:

def myfiles 
if current_user 
    @documents = current_user.documents 
else 
    @documents = Document.all 
end 
end 

查看文件:

<% @documents.each do |document| %> 
<%= link_to document.title, document %>: <%= link_to "Download", document.pdf(:original, false) %> 
<% end %> 
0

Rails find_by返回找到的第一條記錄。您可能正在尋找where

在控制器:

@documents = if params[:user_id] 
    current_user.documents.where(user_id: params[:user_id]) 
else 
    Document.all 
end 

在視圖:

<% @documents.each do |document| %> 
    <%= link_to document.title, document %>: <%= link_to "Download", document.pdf(:original, false) %> 
<% end %> 

http://apidock.com/rails/ActiveRecord/FinderMethods/find_by http://apidock.com/rails/ActiveRecord/QueryMethods/where

+0

這仍然顯示所有文件,而不是與單個用戶 –

+0

哪裏PARAM相關的文件:USER_ID從何而來? – codyeatworld