2011-09-03 38 views
0

我正在嘗試在用戶當前頁面上實現相關文章。我不使用太陽黑子或類似的東西。我已經嘗試了Uchenna Okafor的這段代碼,但是我得到一個錯誤。相關文章在Ruby on Rails中

在這個模型中,我有

#Related Search 
def self.related_search(query, join = "AND") 
    find(:all, :conditions => related_search_conditions(query, join)) 
end 

def self.related_search_conditions(query, join) 
    query.split(/\s+/).map do |word| 
     '(' + %w[name instructions].map { |col| "#{col} LIKE #{sanitize('%' + word.to_s + '%')}" }.join(' OR ') + ')' 
    end.join(" #{join} ") 
end 

在show.html.erb我有

<%= @recipe.related_search %> 

我的錯誤信息是

NoMethodError in Recipes#show 

Showing /Users/sigidis/Ruby/food/app/views/recipes/show.html.erb where line #129 raised: 

undefined method `related_search' for #<Recipe:0x10d4980a0> 

Extracted source (around line #129): 

126: <hr /> 
127: 
128: 
129: <%= @recipe.related_search %> 
130: 
131: 
132: <hr /> 

Rails.root: /Users/sigidis/Ruby/food 
Application Trace | Framework Trace | Full Trace 

app/views/recipes/show.html.erb:129:in `_app_views_recipes_show_html_erb__699416749_2260079280_0' 
app/controllers/recipes_controller.rb:82:in `show' 

Request 

Parameters: 

{"id"=>"35"} 

Show session dump 

Show env dump 
Response 

Headers: 

None 

有人能幫助我,我我是Rails的新手,我很感激任何幫助。提前致謝。

參考文獻。 [http://stackoverflow.com/q/7086092/812668][1]

回答

1

看起來你可能會混淆實例方法和類方法。我不知道您是如何創建@recipe,但請嘗試刪除self.related_searchself.related_search_conditions中的self

編輯:

好吧,我想我明白多一點。首先,我假設這些方法在您的recipe.rb模型中,並且您用class Recipeend包圍了它們。其次,@recipe沒有定義。所以請使用Recipe來代替這個類。最後,您的方法至少需要傳遞第一個參數,在這種情況下是搜索查詢。因此請嘗試以下操作:Recipe.related_search("QUERY HERE")

+0

我仍然得到相同的錯誤。我是否需要在我的控制器中聲明任何內容? – Benjamin

+0

請檢查我的編輯,看看是否回答你的問題。 – VNO

+0

我想我明白你的意思。我有一個名爲recipe.rb的控制器,這就是上面代碼的地方。我試圖展示類似於當前食譜的食譜。我曾嘗試你的方法,我也得到「引發ArgumentError在食譜#顯示 錯誤的參數數目(0 1) 提取的源(左右線#129): 126:


129:<%= Recipe.related_search% > 132:
應用/視圖/食譜/ show.html.erb:129:在'related_search」 應用/視圖/食譜/ show.html.erb:129:在'_app_views_recipes_show_html_erb__699416749_2189106480_0' 應用程序/控制器/ recipes_controller.rb:90:在'show' ' – Benjamin