2016-06-28 81 views
1

,所以我有这样的代码,而我的目标是任何空字符串转换为null红宝石如何修改参数

def convert_empty_strings_to_null 
    if request.patch? || request.post? 
    convert_empty_strings_to_null_rec(request.params) 
    end 
end 

def convert_empty_strings_to_null_rec(param) 
    param = nil if param.empty? if param.is_a?(String) 
    param.all?{|v| convert_empty_strings_to_null_rec v} if param.is_a?(Array) 
    param.all?{|k,v| convert_empty_strings_to_null_rec v} if param.is_a?(Hash) 
end 

但我是新来的Ruby on Rails的,我发现它,它通过发送PARAMS价值,而不是通过引用,所以没有变化的参数,我如何解决这个问题?

+0

注意'呢?'不替代任何东西。改用'map'。在散列的情况下,使用'param.map {| k,v | [x,y]} .to_h'。 – Raffael

回答

3

我认为由“空”你的意思是零用绳子,这意味着仅由空白的字符串应该原封不动。 (否则blank?strip将是你的朋友。)

def convert_empty_strings_to_nil 
    if request.patch? || request.post? 
    request.params.each do |key, value| 
     request.params[key] = convert_empty_strings_to_nil_rec(value) 
    end 
    end 
end 

def convert_empty_strings_to_nil_rec(param) 
    case param 
    when String 
    param.empty? ? nil : param 
    when Array 
    param.map{ |v| convert_empty_strings_to_nil_rec(v) } 
    when Hash 
    param.map{ |k,v| [k, convert_empty_strings_to_nil_rec(v)] }.to_h 
    else 
    param 
    end 
end 
+0

这将解决这个问题,但显然运算符'='没有为params定义,是否有一种方法来迭代params并更改元素本身而不创建新对象? – user2968505

+0

有两种方法:(1)将返回的修改过的参数哈希存储在新的实例变量中并使用它们。 (2)是的,知道'request.params'总是一个散列,我们可以在原地修改它的值。我应该详细说明吗? – Raffael

+0

谢谢我通过调用request.params的第一级递归调用来解决它的每个值 – user2968505

3

首先,这是你的convert_empty_strings_to_null_rec方法应该如何,对于保持持久的变化:

def convert_empty_strings_to_null_rec(param) 
     if param == "" 
     updated_param == nil 
     elsif param.is_a?(Array) 
     updated_param == param.map{|x| nil if x.empty? }   
     elsif param.is_a?(Hash) 
     updated_param = {} 
     param.each do |k, v| 
      if v.empty? 
       updated_param[k] = nil 
      else 
       updated_param[k] = v 
      end 
     end 
     end 
     return updated_param 
end 

而且,我从你的问题假设convert_empty_strings_to_null是一种操作方法。它应该被更新以捕获方法返回的内容convert_empty_strings_to_null_rec

def convert_empty_strings_to_null 
    if request.patch? || request.post? 
    updated_params = convert_empty_strings_to_null_rec(request.params) 
    end 
    # you can use the updated_params here on in this action method 
end 

希望它可以帮助:)

+0

很好的答案bro – nik