-
Notifications
You must be signed in to change notification settings - Fork 8
Relationships
Jasiek Matusz edited this page Dec 6, 2019
·
1 revision
Passing a resource that is a single entity in relationships tree will make JsonApi::Parameters assume that it is a belongs_to
relationship.
Example:
class Movie < ActiveRecord::Model
belongs_to :director
end
Request body:
{
data: {
type: 'movies',
attributes: {
title: 'The Terminator',
},
relationships: {
director: {
data: {
id: 682, type: 'directors'
}
}
}
}
}
Will translate to:
{
movie: {
title: 'The Terminator',
director_id: 682
}
}
Example:
class Movie < ActiveRecord::Model
belongs_to :director
accepts_nested_attributes_for :director
end
Request body:
{
data: {
type: 'movies',
attributes: {
title: 'The Terminator',
},
relationships: {
director: {
data: {
id: 682, type: 'directors'
}
}
}
},
included: [
{
type: 'directors',
id: 682,
attributes: {
name: 'Some guy'
}
}
]
}
Will translate to:
{
movie: {
title: 'The Terminator',
director_attributes: { id: 682, name: 'Some guy' }
}
}
Passing a resource that is a an array of entities in relationships tree will make JsonApi::Parameters assume that it is a has_many
relationship.
Example:
class Movie < ActiveRecord::Model
has_many :genres
end
Request body:
{
data: {
type: 'movies',
attributes: {
title: 'The Terminator',
},
relationships: {
genres: {
data: [{
id: 1, type: 'genres'
},
{
id: 2, type: 'genres'
}]
}
}
}
}
Will translate to:
{
movie: {
title: 'The Terminator',
genre_ids: [1, 2]
}
}
Example:
class Movie < ActiveRecord::Model
has_many :genres
accepts_nested_attributes_for :genres
end
Request body:
{
data: {
type: 'movies',
attributes: {
title: 'The Terminator',
},
relationships: {
genres: {
data: [{
id: 1, type: 'genres'
}]
}
}
},
included: [
{
type: 'genres',
id: 1,
attributes: {
name: 'Genre one'
}
}
]
}
Will translate to:
{
movie: {
title: 'The Terminator',
genres_attributes: [{ id: 1, name: 'Genre one' }]
}
}