Search code examples
ruby-on-railsstrong-parametersactioncontroller

Accessing value(s) of ActionController Parameters hash


I'm having trouble with parameters in an app upgraded from 4.2 to 5.1. I have permitted my parameters, but as the documentation states, I'm getting back an object for my hash array, but can't seem to access the values of it. How can I just get the value of this object?

    {"_method"=>"delete",   "authenticity_token"=>"Z6ZqriiuXu6ODDqhGgocGiaN12rjKD6pUB6n/2v+CABZDAjwLzwczsMM3nM8f0PI0nww43o5mlC35HK+9PVa8w==",
    "domain_name"=>"test.testmodule2.com.",
    "hosted_zone_id"=>"/hostedzone/XXXXXXXXXX",
    "ttl"=>"3600",
    "type"=>"A",
    "value"=>[{"value"=>"1.1.1.1"}],
    "id"=>"/hostedzone/XXXXXXXXXX"}

def record_params
    params.permit!([:hosted_zone_id, :domain_name, :type, :ttl, :alias, :value]).to_h!
end


def destroy
    value = params[:value]
    # returns [<ActionController::Parameters {"value"=>"1.1.1.1"} permitted: true>]
    # would like it to return [{"value"=>"1.1.1.1"}]
end

Solution

  • If that hash is the value of params[:value], then access the value key inside, like:

    params[:value] = {
      "_method"=>"delete",   
      "authenticity_token"=>"...",
      "domain_name"=>"test.testmodule2.com.",
      "hosted_zone_id"=>"/hostedzone/XXXXXXXXXX",
      "ttl"=>"3600",
      "type"=>"A",
      "value"=>[{"value"=>"1.1.1.1"}],
      "id"=>"/hostedzone/XXXXXXXXXX"
    }
    
    params['value']['value'][0]['value']
    # => "1.1.1.1"
    params['value']['value'][0].keys
    # => ["value"]