0

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)?

Victor Ferreira
  • 6,151
  • 13
  • 64
  • 120

2 Answers2

1

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
Dharam Gollapudi
  • 6,328
  • 2
  • 34
  • 42
1

I hope, you have slug column in database.

class Category < ActiveRecord::Base
  has_many :posts

  before_save do
    self.slug = name.gsub(' ', '-').downcase
  end
end
7urkm3n
  • 6,054
  • 4
  • 29
  • 46