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

2415 views ruby-on-rails
-3

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:

{
 "drinks":"true"
 "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)
   resource.save
   redirect_to admin_group_path(resource)
end

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
       binding.pry
     end
    end
    resource.save
    binding.pry
    render('admin/groups/show', { group: group})
end

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 
  <ul>
    <li>
    <%= hidden_field_tag 'view_bank_accounts', false %>
    <%= check_box_tag 'view_bank_accounts', checked = true %> View Bank Accounts 
</li>

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

12

!!string

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?

JD

Please login first before posting an answer.