Kush
Kush

Reputation: 31

undefined method `where' for nil:NilClass when trying to do an advanced search ruby

I am trying to set up an advanced search on the contracts section of my landlord management application.

So far i have followed the following tutorial but still not able to get anywhere.

The search form displays correctly but as soon as i search anything i get error mentioned in title.

app/models/search.rb:11:in search_contracts' app/views/searches/show.html.haml:3:in_app_views_searches_show_html_haml__746758187_75961032'

search.rb

class Search < ActiveRecord::Base

def search_contracts

@contracts = Contract.all

contracts = contracts.where(["first_name LIKE ?", first_name]) if first_name.present?
contracts = contracts.where(["last_name LIKE ?", last_name]) if last_name.present?
contracts = contracts.where(["balance >= ?", min_balance]) if min_balance.present?
contracts = contracts.where(["balance >= ?", max_balance]) if max_balance.present?
contracts = contracts.where(["unpaid_rent LIKE ?", unpaid_rent]) if unpaid_rent.present?

return contracts
end
end

search_controller

class SearchesController < ApplicationController

def new
@search = Search.new
end

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

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


private

def search_params
params.require(:search).permit(:first_name, :last_name, :min_balance, 
:max_balance, :unpaid_rent)
end

end

Upvotes: 0

Views: 61

Answers (1)

jvillian
jvillian

Reputation: 20263

You instantiate @contracts, but not contracts:

class Search < ActiveRecord::Base

  def search_contracts
    @contracts = Contract.all

    contracts = contracts.where(["first_name LIKE ?", first_name]) if first_name.present?
    contracts = contracts.where(["last_name LIKE ?", last_name]) if last_name.present?
    contracts = contracts.where(["balance >= ?", min_balance]) if min_balance.present?
    contracts = contracts.where(["balance >= ?", max_balance]) if max_balance.present?
    contracts = contracts.where(["unpaid_rent LIKE ?", unpaid_rent]) if unpaid_rent.present?

    return contracts
  end
end

So, contracts.where will throw the undefined method error since contracts is nil.

Also, it seems a little weird that Search inherits from ActiveRecord::Base based on the code you've posted. But, maybe there's more going on than meets the eye.

Upvotes: 2

Related Questions