ruby-on-railsruby-on-rails-5strong-parameters

ActionController::Parameters converts integer to string


I have defined user_params in rails 5, like this:

def training_plan_params
  params.require(:training_plan).permit(
    :training_plan_id, 
    :sport_id, 
    :distance,
    lastTrainingStatus: [:duration,:reps,:type,:level],
    trainings: [:text, :order, :level],
    modified: [:level,:duration]
  )
end

but when i send the params to rails, like this:

{ training_plan: { sport_id: 2, distance: 900 } }

it doesn't retrieve the distance in the controller as integer, like this:

=> <ActionController::Parameters {"sport_id"=>"2", "distance"=>"900"} permitted: true>

=> training_plan_params[:distance]
=> "900"

is there a way to keep its type and not converts it to string?


Solution

  • Was dealing with the same issue today, and I did some searching around. I found this post: Rails test is converting my array of ints to an array of strings

    Basically, the issue is with the way you're (we're) using ActionDispatch::IntegrationTest, not with ActionController::Parameters. I solved this by converting the input to my PUT/POST call with .to_json and providing headers: { 'Content-Type': 'application/json' } to the PUT/POST call. That then led to the test router treating my data as json and preserving the typings, rather than defaulting to treating things as text.