Nested Objects With Strong Parameters In Rails

Posted By Weston Ganger

I was working on an application that used a JSONB column and I was storing a lot of nested objects. One issue I came across was trying to get strong parameters to work with the nested objects, it would always complain.

Heres some example data:


{
  "name": "my name",
  "user_settings": {
    "mute": true,
    "theme": "red"
  }
}

Heres some wrong answers followed by the correct answer to this issue.


# WRONG
params.require(:user).permit(:name, :user_settings)

# WRONG
params.require(:user).permit(:name, user_settings: {})

# WRONG
params.require(:user).permit(:name, user_settings: {:mute, :theme})

# CORRECT
params.require(:user).permit(:name, user_settings: [:mute, :theme])

So as you can see you use the same syntax you would for arrays for the objects. So using the same permit method would also work for this data.


{
  "name": "my name",
  "user_settings": [
    {
      "theme": "red"
    },
    {
      "mute": true
    }
  ]
}


Related External Links:

Article Topic:Software Development - Rails

Date:November 08, 2016