1

I am trying to create a simple search feature and getting a wrong number of arguments (2 for 0..1) error. I've followed every simple search rails tutorial to see what I might be doing wrong and had no luck debugging.

Also to note (which might be the reason for this error), I am using ActiveResource to pull records from an API for my Job model.

This is what I have:

# jobs_controller.rb
def index
  if params[:search]
    #ActiveResource does not have an .order which led me to use the code below.
    @jobs = Job.search(params[:search]).sort_by(&:posted).reverse
  else
    @jobs = Job.find(:all).sort_by(&:posted).reverse
  end
end

# job.rb
def self.search(search)
  where("city LIKE ?", "%#{search}")
end


# views/jobs/index.html.erb
<%= form_tag(jobs_path, :method => "get", id: "search-form") do %>
  <%= search_field_tag :search, params[:search], placeholder: "Search Jobs" %>
  <%= submit_tag "Search", name: nil %>
<% end %>

<% if @jobs.present? %>
  <% @jobs.each do |job| %>
    <div>
      <%= link_to job.title, job_path(job) %>
    </div>
  <% end %>
<% else %>
  There are no posts containing the term(s) <%= params[:search] %>.
<% end %>

Error Trace:

Processing by JobsController#index as HTML
  Parameters: {"utf8"=>"✓", "search"=>"Fort Worth"}
Completed 500 Internal Server Error in 1ms (ActiveRecord: 0.0ms)

ArgumentError (wrong number of arguments (2 for 0..1)):
  app/models/job.rb:16:in `search'
  app/controllers/jobs_controller.rb:4:in `index'

wrong number of arguments (2 for 0..1)

Extracted source (around line #16):
15    def self.search(search)
16      where("city LIKE ?", "%#{search}")
17    end
18  end
mikeymurph77
  • 752
  • 1
  • 11
  • 28

2 Answers2

0

ActiveResource doesn't know how to do where("foo = ?", "bar"), because it is not for SQL queries. Your class does have a where method, but it only takes 0 or 1 arguments, not 2.

Paul A Jungwirth
  • 23,504
  • 14
  • 74
  • 93
  • Hmm that was my fear. So for ActiveResource there is no means to do a search easily? I may have to create my own `where` method? – mikeymurph77 Feb 27 '16 at 18:37
  • @mikeymurph77 May I know why not using ActiveRecord ? – Arup Rakshit Feb 27 '16 at 18:38
  • @ArupRakshit I'm using a fake REST API called [json-server](https://github.com/typicode/json-server). The task is not to use the API to seed your own database, but to GET and POST to the Internal Web Server – mikeymurph77 Feb 27 '16 at 18:42
  • The search would have to be offered by the JSON API. ActiveResource is just a convenient way to call such APIs, but if the API doesn't support it, you're out of luck. Even if it does support it, whether you can use ActiveResource depends on how the API expects you to send queries. – Paul A Jungwirth Feb 28 '16 at 01:08
0

I would check the content of params[:search] to make sure it is the string that you want to include. Also make it explicit that where belongs to Job:

Job.where("city LIKE ?", "%#{search}")
fabriciofreitag
  • 2,843
  • 22
  • 26