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.
It seems that you are getting this error because none of the attributes you check for are set when you first invoke
votsphonebookresultson@search, sofind_votsphonebookresultsreturns nil which gets memoized in@votsphonebookresults, when you then callwhereonnilyou 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, wherefind_votsphonebookresultscallsvotsphonebookresultswhich will in turn callfund_votsphonebookresults, so you'll get a stack overflow once the first issue is fixed.