Ruby Rails : TypeError Converting String to Bool using double bang operator

2415 views ruby-on-rails

I'm trying to convert a json obj value which is supposedly a boolean but since its in json datatype - it must be stored as a string at first. Thus following this format:

 "food": "false"
 "name" : "Denise"

I parsed it like so (ActiveAdmin):

member_action :update_permissions, method: :put do
   resource.json_permissions = JSON.parse(params.to_json)
   redirect_to admin_group_path(resource)

Then in my show for view in Rails:

show do
    resource.json_permissions.each do |key, value|
     if value == "true" || value == "false"
       resource.json_permissions[key][value] = !!value
    render('admin/groups/show', { group: group})

the value is where I'm having a hard time. There's really no function such as to_bool and this work around that I found seems only to work via console but can't be registered correctly if I'm using it this way.

Is there any problem in my code on how to use the double bang operator?

My form looks like this:

<%= hidden_field_tag 'view_accounts', false %>
<%= check_box_tag 'view_accounts', checked = true %> View Accounts 
    <%= hidden_field_tag 'view_bank_accounts', false %>
    <%= check_box_tag 'view_bank_accounts', checked = true %> View Bank Accounts 

Thanks in advance!

answered question

Where is your JSON coming from? Booleans are valid JSON values.

@MarcinKo?odziej directly from formdata params I'll edit what my form looks like

Well, it's not really JSON then, unless you're catching the form submits with JavaScript and sending it using AJAX. What's the purpose for dumping your params into JSON and parsing them into a hash again?

1 Answer



will always return true:

!!"false" # true
!!"true"  # true

You can write your assignment as

resource.json_permissions[key][value] = ( value == "true" )

parenthesis are optional, but they increase readability.

posted this

Have an answer?


Please login first before posting an answer.