Search code examples
jsonruby-on-railsactiverecordruby-on-rails-5

Rails API: Cannot whitelist JSON field attribute


I'm building a rails API with a model containing an attribute data of JSON type. (PSQL)

But when I try to post something like this

{ model: { name: 'Hello', data: { a: 1, b: 2 } } }

Rails thinks a and b are the attributes of a nested data association... It considers then they are unpermitted params. The thing is, { a: 1, b: 2 } is the value of my field data.

How to provide JSON value to an attribute ?

Edit:

The error displayed is:

Unpermitted parameters: name, provider, confidence, location_type, formatted_address, place_id, types, locality, ...

The value of the data attribute is { name: 'Name', provider: 'Provider', ... }

Like I said Rails thinks they are the attributes of a nested data association.

Log: Pastebin


Solution

  • if the keys are unknown in advance this could be a workaround:

    def model_params
       data_keys = params[:model].try(:fetch, :data, {}).keys
       params.require(:model).permit(data: data_keys)
    end
    

    Credit goes to aliibrahim, read the discussion https://github.com/rails/rails/issues/9454 (P.S seems like strong parameters will support this use case in Rails 5.1)