jsonapi-rb / jsonapi-parser

Validate JSON API documents.
http://jsonapi-rb.org
MIT License
27 stars 10 forks source link

Document only works for hash - incompatible with Rails 5 #5

Closed cilim closed 7 years ago

cilim commented 7 years ago

I'm trying to use the jsonapi-rails gem to deserialize the incoming params on an HTTP request, but it's not working as expected.

I tried 2 approaches:

Firstly I followed the instructions from the guides and tried using the default JSONAPI::Deserializable::Resource.call(json_hash) like this:

class AuthorsController < ApplicationController
  def create
    respond_with Author.create(author_params), class: AuthorSerializer
  end

  private

  def author_params
    JSONAPI::Deserializable::Resource.call(params)  
  end

but since the JSONAPI::Parser::Resource is expecting a hash an error is raised.

The second approach is using the deserializable_resource on the controller level:

class AuthorsController < ApplicationController
  deserializable_resource :author, only: :create

  def create
    respond_with Author.create(author_params), class: AuthorSerializer
  end

  private

  def author_params
    params.require(:author).permit(:name)
  end

When I try it like this I get ActionController::ParameterMissing: param is missing or the value is empty: author when inspecting the author_params. If I inspect the params they are looking like this:

ActionController::Parameters {"data"=>{"type"=>"authors", "attributes"=>{"name"=>"Author name"}}, "controller"=>"api/v1/authors", "action"=>"create"} permitted: false>

which means that the desiralization on the params didn't occur.

Any guidance would be helpful. I'm using ruby 2.3.1p112 and Rails 5.0.1

beauby commented 7 years ago

Hi @cilim. The second approach is the supported one for rails. I will look into your issue ASAP, but in the meantime, you can use a workaround based on your first approach: just use params.to_unsafe_h in order to get a hash from the parameters.

beauby commented 7 years ago

Also, as this issue is rails-specific, would you mind moving it to jsonapi-rb/jsonapi-rails?

cilim commented 7 years ago

Hi @beauby. Thanks for the help! I'll also transfer this issue to jsonapi-rails.