All threads / Issue with Hash Serialization during update
Ask A Question

Notifications

You’re not receiving notifications from this thread.

Issue with Hash Serialization during update

Ben Densmore asked in Rails

Hi all,
I am working on fixing an issue that came up in our app and have been struggling to nail this one down.

I have a Company model that is a one to one with a FileCompleteness model so I have


class Company < ApplicationRecord
  has_one :file_completenes
end

class FileCompleteness < ApplicationRecord
  belongs_to :company
end

I have an attribute on my FileCompleteness model called "custom_documents" that is setup as text column and is set to

serialize :custom_documents, Hash

The way it's stored in the database is like:

cd_document_1:
name: "Custom Document"
required: 0

The initial bug I ran into is that when the update action runs, it's looking for an attribute called "cd_document_1" which doesn't exist because that is stored in the "custom_documents" column but the form that has the checkbox to toggle the required attribute was being stored with the name "cd_document_1" or whatever custom name is given to that document.

So in the form, I changed it to use the fields_for helper which now kind of works, but I'm running into 2 issues.

Form looks like:

<%= f.fields_for :file_completeness do |setting| %>
     <%= setting.fields_for :custom_documents do |cd| %>
       <%= cd.fields_for field  do |fd| %>
         <%= fd.hidden_field :name,  value: file_completeness.custom_documents[field.to_s]&.fetch(:name) %>
          <%= fd.smarty_on_off_switch(:required) %>
    <% end %>
  <% end %>
<% end %>

If I look at the checkbox in dev tools the form field name is the following:

company[file_completeness_attributes][custom_documents][cd_document_1][required]
  1. The data is going from looking like:

cd_document_1:
name: Custom Document
required: 0

To:

-- !ruby/hash:ActiveSupport::HashWithIndifferentAccess
cd_document_1: !ruby/hash:ActiveSupport::HashWithIndifferentAccess
name: Custom Document
required: '1'

And the other issue is that the required attribute is being turned into a string rather than a boolean.

Does anyone have suggestions on how I can make this behave as intended?

Thank you,
Ben

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 68,099+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more. Icons by Icons8

    © 2022 GoRails, LLC. All rights reserved.