user1801879
user1801879

Reputation: 822

Passing json parameters to rails api

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.

Upvotes: 2

Views: 3486

Answers (1)

K M Rakibul Islam
K M Rakibul Islam

Reputation: 34336

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.

Upvotes: 3

Related Questions