2

I'm using jquery's .ajax method to make a get call to ruby on rails api. The body of get call includes a boolean variable. However this boolean variable keeps getting converted to string on rails side. I'm using correct contentType when making the request.

Here is my javascript ajax call:

                var postBody = {male: true}
                var request = $.ajax({
                    method: "GET",
                    url: "/biographies/getAll",
                    dataType: 'json',
                    contentType: 'application/json',
                    data: postBody
            });

On Ruby on rails controller side, I'm using:

params[:male]

However params[:male] returns "true" string instead of true boolean.

According to Ruby on Rails api:

If the "Content-Type" header of your request is set to "application/json", Rails will automatically convert your parameters into the params hash, which you can access as you would normally. http://guides.rubyonrails.org/action_controller_overview.html#json-parameters

Does anyone has any idea why it would not convert json request to boolean but keep it as string.

thanks.

1 Answer 1

3

In Rails, parameter values are always strings; Rails makes no attempt to guess or cast the type. You have to modify your code logic to adjust with this Rails behaviour. e.g.:

params[:male] == 'true'

See this for reference.

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

2 Comments

That seems to be ok but i think json allow booleans and so there should be some way to keep it as boolean
Even though the original value is boolean, when it passed as a Rails params, it becomes a string and is processed by the Rails controller and in the controller side, params[:male] will always be string. If you know how to keep it as boolean, please let me know, I would learn something new then :)

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.