Skip to content

Instantly share code, notes, and snippets.

@sebyx07
Last active March 19, 2016 13:37
Show Gist options
  • Save sebyx07/99d28d45f26898aad771 to your computer and use it in GitHub Desktop.
Save sebyx07/99d28d45f26898aad771 to your computer and use it in GitHub Desktop.
# Serializer classes
class Job < JSONAPISerializer
attributes :name
end
class PersonSerializer < JSONAPISerializer
attributes :name, :age
has_many :jobs, path: :current_jobs, included: true
end
# simple object
person = OpenStruct.new({id: 1, name: 'Cata', age: '20', current_jobs: [{name: 'Programer', id: 1}]})
# call from a controller
render :json, PersonSerializer.new(person)
=begin
# Output
{
"data": [{
"type": "persons",
"id": "1",
"attributes": {
"name": "Cata",
"age": 20
},
"relationships": {
"jobs": [
{
"data": {"id": "1", "type": "jobs"}
}
]
}
}],
"included": [
{
"type": "jobs",
"id": "1",
"attributes": {
"name": "Programer"
}
}
]
}
=end
# call from a controller. but now we want only the name in the response, without the jobs and age
render :json, PersonSerializer.new person do
attributes :name
has_many :jobs, disabled: true
end
=begin
{
"data": [{
"type": "persons",
"id": "1",
"attributes": {
"name": "Cata"
}
}]
}
=end
# Normalizer
class PersonNormalizer < JSONAPINormalizer
attributes :name
has_many :jobs, path: :current_jobs, normalizer: 'JobsNormalizer'
nested_attibute :address do
attributes :city
nested_attibute :street do
attributes :postal_code
end
end
end
class JobsNormalizer < JSONAPINormalizer
attributes :name
end
=begin
# Input
# POST /persons
{
"data": [{
"type": "persons",
"id": "1",
"attributes": {
"name": "Cata",
"age": 20
}
},
"relationships": {
"jobs": [
{
"data": {"id": "1", "type": "jobs"}
}
]
}
}],
"included": [
{
"type": "jobs",
"id": "1",
"attributes": {
"name": "Smenar"
}
}
]
}
=end
# override the normalizer, not to read the jobs
def create
person_attributes = PersonNormalizer.new params do
attributes :name, :age
has_many :jobs, disabled: true
end
person = Person.new(person_attributes.person)
jobs = person_attributes.jobs.map do |attr|
Job.new(attr)
end
transaction do
person.save
jobs.each(&:save)
end
end
def create
person_attributes = PersonNormalizer.new params
person = Person.new(person_attributes.person)
jobs = person_attributes.jobs.map do |attr|
Job.new(attr)
end
transaction do
person.save
jobs.each(&:save)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment