3

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?

2
  • From the doc on Hash and Array parameters: ... Rails makes no attempt to guess or cast the type. If you depend on the object type after receiving the params, you'll have to make the "cast" manually. You can add what you're trying to do, e.g. Active Record accepts strings when using where or other methods to ask for integer columns, so you don't need to do any conversion. Commented Dec 1, 2019 at 10:53
  • yes, but it didn't convert automatically; when i do something like training_plan_params[:distance]/10.0 ,produces a type error, because "900" is a string. But, when i define permitted params like this permitted_params = ActionController::Parameters.new({as_id: 1, asnot_id: '1'}).permit! permitted_params[:as_id] ,produces 1 while permitted_params[:asnot_id] produces "1". so, it keeps the type in a way, but it not when it is send from outside, but rather defined on a rails console. Commented Dec 1, 2019 at 11:28

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.