Make blank params[] nil

前端 未结 13 680
半阙折子戏
半阙折子戏 2020-12-13 18:36

When a user submits a form and leaves certain fields blank, they get saved as blank in the DB. I would like to iterate through the params[:user] collection (for example) an

13条回答
  •  忘掉有多难
    2020-12-13 19:10

    You could do this using inject, which is obvious as to what is happening.

    params = params.inject({}){|new_params, kv| 
      new_params[kv[0]] = kv[1].blank? ? nil : kv[1]
      new_params
    }
    

    There is also a hack you can do with merge by merging with itself, and passing a block to handle the new value (although this isn't really the intended use for it, but it is more concise)

    params.merge(params){|k, v| v.blank? ? nil : v}
    

提交回复
热议问题