ruby-grape / grape

An opinionated framework for creating REST-like APIs in Ruby.
http://www.ruby-grape.org
MIT License
9.89k stars 1.22k forks source link

Cannot use JSON field with Hashie::Mash #647

Closed sdbondi closed 10 years ago

sdbondi commented 10 years ago

I want to save a JSON structure (Postgres JSON field) from an api request from a param called data.

requires :data, type: Hash

// << JSON sent as data param >>
{
 "data": [{"name": "foo"}, {"name":"bar"}],
"id": "1",
"item": {"foo": "bar"}
}

However when updating the ActiveRecord record the data array still contains Hashie::Mashes. I've tried params[:data].to_hash and params[:data].to_json.

"data": [#<Hashie::Mash ... > etc etc]

A normal ruby hash would be great, or raw json.

Thanks :)

dblock commented 10 years ago

So you want a deep hash? Can you maybe write a test within Grape that reproduces this problem? Thx.

sdbondi commented 10 years ago

Will do sometime this week - You thinking something like: requires :data, type: DeepHash ?

dblock commented 10 years ago

I think a type: Hash should make it a Hash without any additional work. I don't know what would break if that happens, but my first thought is that this is a bug.

sdbondi commented 10 years ago

My mistake!

Was using a strong param helper to access the params, the to_hash method does not 'unhashiemash' the deep arrays. (As it itself is not a Hashie::Mash)

      def permitted_params
        @permitted_params ||= declared(params, include_missing: false)
      end

So I change it to this:

      def permitted_params
        @permitted_params ||= Hashie::Mash.new(declared(params, include_missing: false))
      end

Feature request: Would it make sense to have a permitted_params helper built-in to Grape which uses the params definition to white-list the params hash?

dblock commented 10 years ago

Possibly. Open a PR/Issue? We can discuss it there.