Victor Ferreira Victor Ferreira - 6 months ago 17
Ruby Question

Change or add attributes to model on create/edit with JSONAPI Rails gem

I'm trying to figure out how to use this jsonapi-resources gem but I'm finding it quite difficult.

Let's say I just submitted an object like:

{"name":"My product","price":"15.00"}


But what I want to be saved in the database is something like:

{"name":"My Product","price":"15.00","slug":"my-product","series":301234351}


In other words, I want to intercept the creation or the update and add or alter the data being sent.

In my particular case I got a "Category" model as following:

Controller

class CategoriesController < ApplicationController
#before_action :doorkeeper_authorize!
end


Model

class Category < ActiveRecord::Base
has_many :posts
end


Resource

class CategoryResource < JSONAPI::Resource
attribute :name #,:slug
has_many :posts
end


Route

jsonapi_resources :categories


How can I add, for example, slug, short-name, last_update to the Category model (assuming it was not passed by the client)?

Answer

Try the following:

class CategoryResource < JSONAPI::Resource
  attribute :name #,:slug
  has_many :posts

  before_save do
    # add logic to change or add attributes to model on create/edit 
    # for example
    @model.slug = # logic to assign the slug
    @model.series = # logic to assign the series
  end
end