我正在试图弄清楚如何使用这个jsonapi-resources宝石,但我发现它很难。
假设我刚刚提交了一个像:
这样的对象{"name":"My product","price":"15.00"}
但是我想要保存在数据库中的是:
{"name":"My Product","price":"15.00","slug":"my-product","series":301234351}
换句话说,我想拦截创建或更新,并添加或更改正在发送的数据。
在我的特定情况下,我得到了一个“类别”模型如下:
控制器
class CategoriesController < ApplicationController
#before_action :doorkeeper_authorize!
end
模型
class Category < ActiveRecord::Base
has_many :posts
end
资源
class CategoryResource < JSONAPI::Resource
attribute :name #,:slug
has_many :posts
end
路线
jsonapi_resources :categories
如何将slug,short-name,last_update添加到Category模型中(假设它没有被客户端传递)?
答案 0 :(得分:1)
尝试以下方法:
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
答案 1 :(得分:1)
我希望你在数据库中有slug列。
class Category < ActiveRecord::Base
has_many :posts
before_save do
self.slug = name.gsub(' ', '-').downcase
end
end