undefined method `gsub' for nil:NilClass
Asked Answered
P

4

6

I'm newvbie in ruby on rails.. I'm having problem with gsub.. I everytime I go to the list of my store page it says "undefined method `gsub' for nil:NilClass"..

here is mycode :

def self.search(search_val, page = 1)
    @search_val = search_val.gsub("'", "\\\\'")
    search_query = "store_id LIKE '%#{ @search_val }%' OR english_name LIKE '%#{ @search_val }%' OR chinese_name LIKE '%#{ @search_val }%'"
select("jos_store.id, store_id, english_name, chinese_name, store_manager, delivery_area,year, week").joins("LEFT OUTER JOIN (SELECT id as store_replenishment, store, MAX(stock_movement) AS stock_movement FROM jos_store_replenishment GROUP BY store) AS replenishment ON replenishment.store = jos_store.id").joins("LEFT OUTER JOIN jos_stock_movement ON jos_stock_movement.id = replenishment.stock_movement").where(search_query).order("year DESC, week DESC").paginate :page => page, :per_page => 15  
  end

thanks in advance

Phenoxide answered 16/7, 2012 at 5:24 Comment(0)
T
21

A good practice is doing .to_s when you are using string methods.

Triode answered 16/7, 2012 at 20:25 Comment(2)
thanks guys but I already figure out the answer... i put a " unless search_val.blank? " before my gsub eg. unless search_val.blank? @search_val = search_val.gsub("'", "\\\\'")Phenoxide
Why the owner does not mark one of the Answers as actually accepted answer? At least, the explanations really worked for me!Cryptic
S
4

You can use the & operator on search_val. It allows you to avoid null pointer exceptions without adding additional checks or using to_s to convert a string to a string.

So, you'll have something like this:

@search_val = search_val&.gsub("'", "\\\\'")

You can read more on the safe navigation operator here: http://mitrev.net/ruby/2015/11/13/the-operator-in-ruby/

Sexless answered 20/2, 2018 at 21:29 Comment(0)
M
3

This means that search_val is in fact nil. You can easily verify this by printing out the value of search_val.

Mango answered 16/7, 2012 at 5:43 Comment(0)
H
0

I'm not sure if this is your case, but the same undefined method gsub for nil:NilClass error happened with me after a few rollbacks and migrations.

Then, I restarted the server and works. Maybe this could be the case for some people that reached this topic searching on Google.

Hyperextension answered 10/6, 2022 at 18:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.