Search code examples
ruby-on-railsrubyjsonember.jsjson-api

Cleaner way to have params with Rails and JSON API


I have an Ember application for client side and Rails for server side. I decided to use json-api because I think it is a standard for both. When I save a model, Ember send this kind of data :

{ "data" =>
  { "relationships" =>
    { "users" =>
      { "data" =>
        [ { "type" => "users", "id" => "2" } ]
      }
    },
    "type" => "trails"
  },
  "controller" => "api/v1/trails",
  "action" => "create"
}

In my controller, I have this method :

  def create
    render json: Trail.create(trail_params)
  end

I can obviously do a method trail_params that change parameters and return the format used by ActiveRecord but I want to know if their is a better way.

I use ActiveModelSerializer but I don't see a built-in solution.

My problem : I don't like the fact than I have to do a parser to deserialize parameters and to have {users: [2]} as ActiveRecord want.

What is the best practice?


Solution

  • Maybe a little late, but...

    You're right that JSON API support isn't yet built into Rails' AMS. However, there are a few Ruby libraries out there that make it really easy to build JSON API-compliant APIs on top of ActiveRecord. Perhaps the best is JSONAPI::Resources, but there's also Oat and, very soon a different AMS library.