Ruby-on-rails nil:NilClass 的未定义方法`gsub'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11498516/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
undefined method `gsub' for nil:NilClass
提问by Lian
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"..
我是 ruby on rails 的新手.. 我遇到了 gsub 的问题.. 我每次去我的商店页面列表时都会说“未定义的方法 `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
提前致谢
回答by YaBoyQuy
A good practice is doing .to_swhen you are using string methods.
.to_s当您使用字符串方法时,一个好的做法是这样做。
回答by Benjamin Tan Wei Hao
This means that search_valis in fact nil. You can easily verify this by printing out the value of search_val.
这意味着search_val实际上为零。您可以通过打印出 的值轻松验证这一点search_val。
回答by Sergey Smirnov
You can use the &operator on search_val. It allows you to avoid null pointer exceptions without adding additional checks or using to_sto convert a string to a string.
您可以在&上使用运算符search_val。它允许您在不添加额外检查或to_s用于将字符串转换为字符串的情况下避免空指针异常。
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/
您可以在此处阅读有关安全导航操作员的更多信息:http: //mitrev.net/ruby/2015/11/13/the-operator-in-ruby/

