Make blank params[] nil

前端 未结 13 670
半阙折子戏
半阙折子戏 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 18:50

    Here is how I did it.

    def remove_empty_params(param, key)
      param[key] = param[key].reject { |c| c.empty? }
    end
    

    and call it with

    remove_empty_params(params[:shipments], :included_clients)
    

    No need to get super tricky in the model. And this way you can control which params get cleaned up.

    params = {
          "shipments"=>{
            "included_clients" => ["", "4"]
          }
        }
    

    will turn into

    >> params["shipments"]
    => {"included_clients" => ["4"] }
    

提交回复
热议问题