2017-06-03 27 views
0

我有一個rails資源文檔。 這些文件有一個名爲author_ids的屬性,它是一個user_id的數組。如何查找Rails資源鍵是否在其數組中有值?

例子:

@document.author_ids = [1,2,3,4] 

我建立一個顯示所有文件的儀表板。

def dashboard 
@documents = Documents.all 
end 

我希望author_ids內的所有用戶都能查看文檔。 我想做一些類似於下面的操作,我在這裏查找current_user.id的值是否包含在Documents資源的author_id數組中,並將這些文檔列爲@documents。

def dashboard 
@documents = Document.all.where(:author_ids.include?(current_user.id)) 
end 

我知道我不能調用.include?在Key(:author_ids)這是一個數組。我需要幫助遍歷鍵:author_id中的每個值來檢查current_user.id的值是否在:author_id數組內。

+0

你是什麼'property'是什麼意思?它是文檔中的屬性/列還是模型中的方法? –

+0

是的屬性像@ document.author_ids => [1,2,3] –

回答

0

我相信你一定有

class Document 
    has_many :document_authors 
    has_many :authors, through: :document_authors 

那麼這將返回預期的結果

def dashboard 
    @documents = Document.joins(:authors).where(authors: { id: current_user.id}) 
end 
+0

這聽起來像它會工作,但它們是一個問題。我根本不知道authors_ids。基本上我通過電子郵件發送這個文件。 當我按發送按鈕時,我調用create_authors()這是 搜索我的用戶資源以查看我要發送文檔的電子郵件是否存在於數據庫中。如果沒有,我創建一個新用戶並將user_id添加到document.author_ids數組中並更新文檔。如果是這樣,我也將author_id推到數組上並更新文檔。而不是創建另一個模型,我寧願只將值推入數組中。 –

相關問題