使用 JSONAPI Rails gem 在 create/edit 上为模型更改或添加属性
Change or add attributes to model on create/edit with JSONAPI Rails gem
我正在尝试弄清楚如何使用这个 jsonapi-resources gem 但我发现它非常困难。
假设我刚刚提交了一个对象,例如:
{"name":"My product","price":"15.00"}
但是我想保存在数据库中的是这样的:
{"name":"My Product","price":"15.00","slug":"my-product","series":301234351}
换句话说,我想拦截创建或更新并添加或更改正在发送的数据。
在我的特殊情况下,我得到了一个 "Category" 模型,如下所示:
控制器
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 添加到类别模型(假设它没有被客户端传递)?
尝试以下操作:
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
我希望,你在数据库中有 slug 列。
class Category < ActiveRecord::Base
has_many :posts
before_save do
self.slug = name.gsub(' ', '-').downcase
end
end
我正在尝试弄清楚如何使用这个 jsonapi-resources gem 但我发现它非常困难。
假设我刚刚提交了一个对象,例如:
{"name":"My product","price":"15.00"}
但是我想保存在数据库中的是这样的:
{"name":"My Product","price":"15.00","slug":"my-product","series":301234351}
换句话说,我想拦截创建或更新并添加或更改正在发送的数据。
在我的特殊情况下,我得到了一个 "Category" 模型,如下所示:
控制器
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 添加到类别模型(假设它没有被客户端传递)?
尝试以下操作:
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
我希望,你在数据库中有 slug 列。
class Category < ActiveRecord::Base
has_many :posts
before_save do
self.slug = name.gsub(' ', '-').downcase
end
end