Rails: how to sanitize nested object to save to JSONB column?

51 Views Asked by At

Given these strong parameters in a Rails controller:

def user_params
  params.require(:user).permit(details: [{ group: %i[type value] }])
end

How do I sanitize the details array before it's persisted into a JSONB column?

1

There are 1 best solutions below

0
t56k On BEST ANSWER

I wrote a solution for anyone else with a similar problem:

include ActionView::Helpers::SanitizeHelper

# ...

private

def sanitize_details
  return unless details

  self.details = details.map do |group|
    sanitized_details = group['group'].map do |detail|
      { type: sanitize_most(detail['type']), value: sanitize_most(detail['value']) }
    end
    { group: sanitized_details }
  end
end

def sanitize_most(field)
  sanitize(field, tags: %w[a b i strong em], attributes: %w[href rel target])
end