2015-04-12 35 views
1

我試圖爲當前用戶創建一個搜索槽,但在傳入我的.find參數no implicit conversion of Symbol into Integer時得到此錯誤。我將當前用戶參數存儲在@current_user中,並希望查找由該用戶編寫的所有文章(即在名爲user_id的列中搜索current_user.id)。我是新來的紅寶石,無法弄清楚這裏發生了什麼,谷歌搜索,任何幫助表示讚賞。Rails,當在表上使用.find時,沒有將Symbol隱式轉換爲Integer

應用控制器:

helper_method :current_user 

def current_user 
    @current_user ||= User.find(session[:user_id]) if session[:user_id] 
end 

文章控制器:

def manage 
    @article = Article.find(current_user.id[:user_id]) 
end 

user.rb

class User < ActiveRecord::Base 
    attr_accessor :password 
    ... 
    has_many :article 
end 

article.rb

class Article < ActiveRecord::Base 
    belongs_to :user 
end 
+0

'current_user.id'是您要搜索的標識。即'@article = Article.find(current_user.id)'。 – Drenmi

回答

2

你可以改變這

Article.where(user_id: current_user.id) 

但更好的方法是隻使用你所創建的關聯(不將其更改爲has_many :articles第一)

current_user.articles 

find_by_user_idfind_by(user_id: current_user.id)會工作,但只返回一篇文章。

+0

這是最好的答案。使用關聯。 – BigRon

+0

你能解釋一下使用'.where','.find_by_user_id'和'current_user.articles'的區別嗎?說實話,我最喜歡使用這個關聯關係,因爲它是鍵入它的最簡單的方式,但是我想從內存使用,代碼版本等方面聽到(或者閱讀,如果可以鏈接關於此的文檔/指南)參數。在 –

+0

協會是這樣做的慣用方式。任何性能差異將是最小 –

相關問題