Rails hashes with unknown keys and strong parameters

前端 未结 4 1484
旧巷少年郎
旧巷少年郎 2021-01-12 20:09

I have a rails application that stores a serialized hash in a field called properties.

The hashes keys are unknown though, so I don\'t know of a way to

4条回答
  •  心在旅途
    2021-01-12 20:22

    You can use a hash instead of a symbol and define what sub-properties are allowed. This can be seen in the source here:

    case filter
    when Symbol, String
      permitted_scalar_filter(params, filter)
    when Hash
      hash_filter(params, filter)
    end
    

    https://github.com/rails/rails/blob/bdc73a438a97f2e0aceeb745f4a95f95514c4aa6/actionpack/lib/action_controller/metal/strong_parameters.rb#L522

    e.g.

    def user_params
      params.require(:person).permit(:name, :description, :age, properties: [:key, :value])
    end
    

    If you have no idea what is going to be in properties you could use .slice. Note this will accept anything nested in any of the other fields too.

    e.g.

    def user_params
      params.require(:person).slice(:name, :description, :age, :properties) 
    end
    

    These approaches will work on the following params:

    {
      "person": {
        "name": "John",
        "description": "has custom_attributes",
        "age": 42,
        "properties": [
          {
            "key": "the key",
            "value": "the value"
          }
        ]
      }
    }
    

    I've confirmed these will work on Rails 4.2.6

提交回复
热议问题