Rails converts empty arrays into nils in params of the request

后端 未结 6 1859
闹比i
闹比i 2021-02-01 12:20

I have a Backbone model in my app which is not a typical flat object, it\'s a large nested object and we store the nested parts in TEXT columns in a MySQL database.

I wa

6条回答
  •  半阙折子戏
    2021-02-01 12:58

    Here's (I believe) a reasonable solution that does not involve re-parsing the raw request body. This might not work if your client is POSTing form data but in my case I'm POSTing JSON.

    in application_controller.rb:

      # replace nil child params with empty list so updates occur correctly
      def fix_empty_child_params resource, attrs
        attrs.each do |attr|
          params[resource][attr] = [] if params[resource].include? attr and params[resource][attr].nil?
        end
      end
    

    Then in your controller....

    before_action :fix_empty_child_params, only: [:update]
    
    def fix_empty_child_params
      super :user, [:child_ids, :foobar_ids]
    end
    

    I ran into this and in my situation, if a POSTed resource contains either child_ids: [] or child_ids: nil I want that update to mean "remove all children." If the client intends not to update the child_ids list then it should not be sent in the POST body, in which case params[:resource].include? attr will be false and the request params will be unaltered.

提交回复
热议问题