Matt White
Matt White

Reputation: 117

Ruby simple search form error

As a ruby-on-rails beginner, I am creating a very simple app to test a search form. Here is everything:

Person Model

class Person < ActiveRecord::Base

def self.search(search)
 if search
  all(:conditions => ['name LIKE ?', "%#{search}%"])
 else
  all
 end
end

end

Persons controller

class PersonsController < ApplicationController
 def index
  @person = Person.search(params[:search])
 end
end

Person#index

<h1>Persons#index</h1>

<%= form_tag persons_index_path, :method => 'get' do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>

<% end %>

<div>
<% @person.each do |person| %>
<p><%= person.name %><p>
<% end %>
</div>

When I load the index and use the search form, I get this error:

wrong number of arguments (1 for 0)

Extracted source (around line #5): 3 4 5 6 7 8

def self.search(search)
 if search
  all(:conditions => ['name LIKE ?', "%#{search}%"])
 else
  all
 end

No doubt I am making a simple mistake, any suggestions?

Upvotes: 2

Views: 81

Answers (1)

Abdul Baig
Abdul Baig

Reputation: 3721

change you search method to: (minified version)

def self.search(search)
  search.present? ? where('name LIKE ?', "%#{search}%") : all
end

Or your old method: (your same old structure)

def self.search(search)
   if search.present?
     where('name LIKE ?', "%#{search}%")
   else
     all
   end
end

Upvotes: 1

Related Questions