David Correa David Correa - 14 days ago 5
JSON Question

Is it possible to whitelist JSON (as text) in Rails' strong parameters?

Let's say I have this JSON:

{
name: 'David',
tags: {
is_confused: true
}
}


and in a certain model (i.e. User), I can save this directly... but my tags object needs to be saved in a Text column which will later serialize to JSON. Is there any way to do this with strong parameters?

Answer

You can force tags to json before permitting it as a string with strong parameters.

Assuming your object is named "params":

params[:tags] = params[:tags].permit(:is_confused).to_json
final_data = params.permit(:name, :tags)

This uses strong parameters to check the tags field before turning it to a json string so that you can save it as text (and use strong parameters to ensure that it's a string).