gazay / gon

Your Rails variables in your JS
MIT License
3.05k stars 184 forks source link

Array attribute types incorrectly rendered with Jbuilder using key_format! option #265

Open tsmith-dev opened 3 years ago

tsmith-dev commented 3 years ago

When using gon with Jbuilder and the key_format! :camelize :lower option, array database attributes are incorrectly parsed to json. Visiting the .json route displays the correctly parsed JSON from Jbuilder, but the JSON from Gon inside the <head> tag on the page is incorrect.

Example:

Attribute is stored in a database array attribute:

schema.rb

create_table "conditions", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
  t.string "determinant_name"
  t.string "operator"
  t.string "condition_value", default: [], array: true
end

Jbuilder template uses the key_format! option to convert snake_case to camelCase:

_form.json.jbuilder

json.key_format! camelize: :lower
json.rules @rules do |rule|
  json.(rule, :id)
  json.conditionsAttributes rule.conditions do |condition|
    json.(condition, :determinant_name, :condition_value, :operator)
  end
end

Expected result:

rules: [
  {
    id: "a915ba39-fa2e-4a47-ab04-20ecc330080e",
    conditionsAttributes: [
      {
        determinantName: "States",
        operator: "One of These",
        conditionValue: ["Alaska","California"]
      }   
    ]    
  }
]

Actual result:

rules: [
  {
    id: "a915ba39-fa2e-4a47-ab04-20ecc330080e",
    conditionsAttributes: [
      {
        determinantName: "States",
        operator: "One of These",
        conditionValue: ["0"]
      }   
    ]    
  }
]