Ruby on rails JSON API资源关系属性
我有两个相关的模型:Ruby on rails JSON API资源关系属性,ruby-on-rails,json,ruby,json-api,jsonapi-resources,Ruby On Rails,Json,Ruby,Json Api,Jsonapi Resources,我有两个相关的模型: class Item < ActiveRecord::Base belongs_to :carousel end 我的旋转木马资源: module Api module V1 class CarouselResource < JSONAPI::Resource immutable attributes :name, :items def self.records(options =
class Item < ActiveRecord::Base
belongs_to :carousel
end
我的旋转木马资源:
module Api
module V1
class CarouselResource < JSONAPI::Resource
immutable
attributes :name, :items
def self.records(options = {})
user = options[:context][:current_user]
user.carousels
end
end
end
end
要使用json,请使用
json Builder
或ActiveModelSerializers
。为@ashvin所说的内容添加更多帮助。一旦开始使用ActiveModelSerializer
,就可以为项目创建一个,这样,就可以显式指定要使用该序列化程序的代码,并在该文件中设置要在API中公开的属性。祝你好运谢谢你的帮助!!我用@model.items.as_json(仅:[:title,:file,:index])覆盖方法中的项来解决这个问题
{
"data": [
{
"id": "1",
"type": "carousels",
"links": {
"self": "http://localhost:3000/api/v1/carousels/1"
},
"attributes": {
"name": "primary",
"items": [
{
"title": "first item",
"file-url": "url",
"index": 0
},
{
"title": "second item",
"file-url": "url",
"index": 1
}
]
}
}
]
}
module Api
module V1
class CarouselResource < JSONAPI::Resource
immutable
attributes :name, :items
def self.records(options = {})
user = options[:context][:current_user]
user.carousels
end
end
end
end
{
"data": [
{
"id": "1",
"type": "carousels",
"links": {
"self": "http://localhost:3000/api/v1/carousels/1"
},
"attributes": {
"name": "primary",
"items": [
{
"id": 3,
"carousel_id": 1,
"file": {
"url": "url"
},
"title": "first item",
"kind": 0,
"index": 0,
"created_at": "2017-02-23T10:31:53.592-03:00",
"updated_at": "2017-03-01T10:30:52.533-03:00"
},
{
"id": 5,
"carousel_id": 1,
"file": {
"url": "url"
},
"title": "second item",
"kind": 0,
"index": 1,
"created_at": "2017-03-01T10:30:07.011-03:00",
"updated_at": "2017-03-01T10:30:07.011-03:00"
}
]
}
}
]
}