0

I'm getting an error trying to perform a search that was outlined in Railscasts #111 Advanced Search.

The code I have at the moment:

Searches Controller

class SearchesController < ApplicationController
def new
    @search = Search.new
end

def create
    @search = Search.new(search_params)
end

def show
    @search = Search.find(params[:id])
end

private

def search_params
  params.require(:search).permit(:firstname, :surname, :phonenumber, :department, :division, :address, :note)
end
end

show.html.erb

<h1>Search Results</h1>
<%= render @search.votsphonebookresults %>

search.rb

class Search < ActiveRecord::Base
def votsphonebookresults
    @votsphonebookresults ||= find_votsphonebookresults
end

private

def find_votsphonebookresults

    votsphonebookresults = votsphonebookresults.where("firstname like ?", "%#{firstname}%") if firstname.present?
    votsphonebookresults = votsphonebookresults.where("surname like ?", "%#{surname}%") if surname.present?
    votsphonebookresults = votsphonebookresults.where("OfficeNumber like ?", "%#{OfficeNumber}%") if phonenumber.present?
    votsphonebookresults = votsphonebookresults.where("Department like ?", "%#{Department}%") if department.present?
    votsphonebookresults = votsphonebookresults.where("Division like ?", "%#{Division}%") if division.present?
    votsphonebookresults = votsphonebookresults.where("Address like ?", "%#{Address}%") if address.present?
    votsphonebookresults = votsphonebookresults.where("Note like ?", "%#{Note}%") if note.present?
    votsphonebookresults
end
end

I am getting a 'undefined method `where' for nil:NilClass' error when trying to perform the search. The search form is OK, but submitting creates an issue with 'where'

I am performing the search through to a database that is in MS SQL Server. I can display the entries in that database fine everywhere else on my app just fine.

jimps
  • 65
  • 12

1 Answers1

0

It seems that you are getting this error because none of the attributes you check for are set when you first invoke votsphonebookresults on @search, so find_votsphonebookresults returns nil which gets memoized in @votsphonebookresults, when you then call where on nil you get a UndefinedMethod error. More fundamentally, though, the problem with your code in the search class lies in the fact that you have an infinite loop, where find_votsphonebookresults calls votsphonebookresults which will in turn call fund_votsphonebookresults, so you'll get a stack overflow once the first issue is fixed.

Jan Bussieck
  • 1,039
  • 12
  • 26