Reputation: 1629
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
Upvotes: 6
Views: 39535
Reputation: 1
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.
Upvotes: 0
Reputation: 303
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/
Upvotes: 4
Reputation: 793
A good practice is doing .to_s
when you are using string methods.
Upvotes: 21
Reputation: 9691
This means that search_val
is in fact nil. You can easily verify this by printing out the value of search_val
.
Upvotes: 3