Benjamin
Benjamin

Reputation: 2118

Related Articles In Ruby on Rails

I am trying to implement a related article on the user current page. I am not using sunspot or anything like that. I have tried this code by Uchenna Okafor but i get an error.

In the model i have

    #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

On the show.html.erb i have

  <%= @recipe.related_search %>

My error message is

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

Can someone help me out, I am new to Rails and i would appreciate any help. Thanks in advance.

References. [http://stackoverflow.com/q/7086092/812668][1]

Upvotes: 0

Views: 705

Answers (1)

VNO
VNO

Reputation: 3695

Looks like you may be confusing an instance method with a class method. I don't know how you are creating @recipe , but try removing the self in self.related_search and self.related_search_conditions.

EDIT:

Ok, I think I understand a bit more. First, I'm assuming those methods are in your recipe.rb model and you have surrounded them with a class Recipe and end. Second, @recipe has no definition. So use Recipe instead to refer to the class. Lastly, your methods require at least the first argument to be passed, in this case the search query. So try the following: Recipe.related_search("QUERY HERE").

Upvotes: 1

Related Questions