Rails

Nested Objects With Strong Parameters In Rails

Posted by Weston Ganger on November 08, 2016

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:


Posted in Rails and Tagged with strong_parameters rails 


Need help on your next project or application?

I specialize in Ruby-on-Rails, AngularJS, Javascript, Bootstrap, and Hybrid Mobile Apps with Cordova & Ionic.

Contact Me

Recommended Posts