I'm using ActiveModel::Serializer to serialize my json data.
I have three models as follows
class Invoice < ApplicationRecord
has_many :invoiceDetails, inverse_of: :invoice
belongs_to :customer
accepts_nested_attributes_for :invoiceDetails
end
class InvoiceDetail < ApplicationRecord
belongs_to :invoice
belongs_to :product
end
class Product < ApplicationRecord
belongs_to :company
belongs_to :category
belongs_to :user
has_many :invoice_details
end
The serializers are as follows :
class InvoiceSerializer < ActiveModel::Serializer
attributes :id, :total_amount, :balance_amount, :created_at
belongs_to :customer
has_many :invoiceDetails
end
class InvoiceDetailSerializer < ActiveModel::Serializer
attributes :id, :quantity
belongs_to :product
belongs_to :invoice
end
class ProductSerializer < ActiveModel::Serializer
attributes :id, :name, :mrp, :sp, :cp, :stocks, :isPublished
has_one :category
end
When I retrieve an invoice I get the attributes from the associated invoiceDetails model and customer model but the attributes from the product model associated with the invoiceDetails model are missing.
For example if I retrieve an invoice, this is the output :
[
{
"id": 3,
"total_amount": 450,
"balance_amount": 350,
"created_at": "2017-06-27T17:02:20.000Z",
"customer": {
"id": 4,
"company_id": 1,
"name": "vivek",
"isActive": true,
"created_at": "2017-06-27T14:35:50.000Z",
"updated_at": "2017-06-27T14:35:50.000Z",
"mobile": "12345678",
"address": "test",
"pan_number": null,
"tin_number": null,
"party_name": "vipul jwelers"
},
"invoiceDetails": [
{
"id": 4,
"quantity": 1
},
{
"id": 5,
"quantity": 1
}
]
}
]
However if I retrieve invoiceDetail directly I get the associated model attributes.
**[
{
"id": 6,
"quantity": 5,
"product": {
"id": 4,
"name": "Test Prod",
"mrp": 150,
"sp": 130,
"cp": 100,
"stocks": 100,
"isPublished": true
},
"invoice": {
"id": 4,
"total_amount": 3903,
"balance_amount": 3,
"created_at": "2017-07-01T07:45:02.000Z"
}
},
{
"id": 7,
"quantity": 10,
"product": {
"id": 5,
"name": "Test Prod 2",
"mrp": 300,
"sp": 250,
"cp": 200,
"stocks": 10,
"isPublished": true
},
"invoice": {
"id": 4,
"total_amount": 3903,
"balance_amount": 3,
"created_at": "2017-07-01T07:45:02.000Z"
}
}
]**
So for retrieving the nested attributes directly from invoice, do I need to change the relationship among my models?
Has someone encountered the same problems, or any work around you can suggest?
If someone is stuck over this problem, here is what I did :
Whenever I want to retrieve the deeply nested association I add the "include **" keyword in the controller during response.
For example :
def show
cust_id = params[:customer_id]
invoice_id = params[:id]
if cust_id && invoice_id
invoice = Invoice.where(:id => invoice_id, :customer_id => cust_id)
render json: invoice, include: '**', status: 200
else
render json: { errors: "Customer ID or Invoice ID is NULL" }, status: 422
end
end
The include * * will retrieve all the nested attributes for the invoice model using the serializer if defined for the respective models.
Related
In my Rails (api only) learning project, I have 2 models, Group and Artist, that have a many-to-many relationship with a joining model, Role, that has additional information about the relationship. I have been able to save m2m relationships before by saving the joining model by itself, but here I am trying to save the relationship as a nested relationship. I'm using the jsonapi-serializer gem, but not married to it nor am I tied to the JSON api spec. Getting this to work is more important than following best practice.
With this setup, I'm getting a 500 error when trying to save with the following errors:
Unpermitted parameters: :artists, :albums and ActiveModel::UnknownAttributeError (unknown attribute 'relationships' for Group.)
I'm suspecting that my problem lies in the strong param and/or the json payload.
Models
class Group < ApplicationRecord
has_many :roles
has_many :artists, through: :roles
accepts_nested_attributes_for :artists, :roles
end
class Artist < ApplicationRecord
has_many :groups, through: :roles
end
class Role < ApplicationRecord
belongs_to :artist
belongs_to :group
end
Controller#create
def create
group = Group.new(group_params)
if group.save
render json: GroupSerializer.new(group).serializable_hash
else
render json: { error: group.errors.messages }, status: 422
end
end
Controller#group_params
def group_params
params.require(:data)
.permit(attributes: [:name, :notes],
relationships: [:artists])
end
Serializers
class GroupSerializer
include JSONAPI::Serializer
attributes :name, :notes
has_many :artists
has_many :roles
end
class ArtistSerializer
include JSONAPI::Serializer
attributes :first_name, :last_name, :notes
end
class RoleSerializer
include JSONAPI::Serializer
attributes :artist_id, :group_id, :instruments
end
Example JSON payload
{
"data": {
"attributes": {
"name": "Pink Floyd",
"notes": "",
},
"relationships": {
"artists": [{ type: "artist", "id": 3445 }, { type: "artist", "id": 3447 }]
}
}
Additional Info
It might help to know that I was able to save another model with the following combination of json and strong params.
# Example JSON
"data": {
"attributes": {
"title": "Wish You Were Here",
"release_date": "1975-09-15",
"release_date_accuracy": 1
"notes": "",
"group_id": 3455
}
}
# in albums_controller.rb
def album_params
params.require(:data).require(:attributes)
.permit(:title, :group_id, :release_date, :release_date_accuracy, :notes)
end
From looking at https://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html I think the data format that Rails is normally going to expect will look something like:
{
"group": {
"name": "Pink Floyd",
"notes": "",
"roles_attributes": [
{ "artist_id": 3445 },
{ "artist_id": 3447 }
]
}
}
with a permit statement that looks something like (note the . before permit has moved):
params.require(:group).
permit(:name, :notes, roles_attributes: [:artist_id])
I think you have a few options here:
Change the data format coming into the action.
Craft a permit statement that works with your current data (not sure how tricky that is), you can test your current version in the console with:
params = ActionController::Parameters.new({
"data": {
"attributes": {
"name": "Pink Floyd",
"notes": "",
},
"relationships": {
"artists": [{ type: "artist", "id": 3445 }, { type: "artist", "id": 3447 }]
}
}
})
group_params = params.require(:data).
permit(attributes: [:name, :notes],
relationships: [:artists])
group_params.to_h.inspect
and then restructure the data to a form the model will accept; or
Restructure the data before you try to permit it e.g. something like:
def group_params
params_hash = params.to_unsafe_h
new_params_hash = {
"group": params_hash["data"]["attributes"].merge({
"roles_attributes": params_hash["data"]["relationships"]["artists"].
map { |a| { "artist_id": a["id"] } }
})
}
new_params = ActionController::Parameters.new(new_params_hash)
new_params.require(:group).
permit(:name, :notes, roles_attributes: [:artist_id])
end
But ... I'm sort of hopeful that I'm totally wrong and someone else will come along with a better solution to this stuff.
I have a Component class that can be either a Section or Question. A Section can have many Component (i.e. Question).
I'm trying to get the serializer to send back the Component(Section) and its associated Component(Question). Right now, based on my code below, I'm getting back the Question and the Section object that it's associated to (see below). How can I get the serializer to return what I'm expecting?
Response (current):
{"data":
[{"id": 1,
"type": "Section",
"content": "ABC",
"section_id": null,
"section": null
},
{"id": 2,
"type": "Question",
"content": "Q1",
"section_id": 1,
"section":
{"id": 1,
"type": "Section",
"content": "ABC",
"section_id": null
}
},
{"id": 3,
"type": "Question",
"content": "Q2",
"section_id": 1,
"section":
{"id": 1,
"type": "Section",
"content": "ABC",
"section_id": null
}
}]
}
Response (expected):
{"data":
[{"id": 1,
"type": "Section",
"content": "ABC",
"section_id": null,
"section":
{"id": 2,
"type": "Question",
"content": "Q1",
"section_id": 1
},
{"id": 3,
"type": "Question",
"content": "Q2",
"section_id": 1
}
}]
}
ComponentSerializer:
class ComponentSerializer < ActiveModel::Serializer
belongs_to :section
attributes :id,
:type,
:content,
:section_id
end
SectionSerializer:
class ComponentSerializer < ActiveModel::Serializer
has_many :components
attributes :id,
:type,
:content,
:section_id
end
component.rb (model):
class Component < ApplicationRecord
# == Associations ==========================
belongs_to :project
belongs_to :section,
class_name: 'Section',
foreign_key: :section_id,
optional: true
end
section.rb (model):
class Section < Component
# == Associations ==========================
has_many :components,
class_name: 'Component',
foreign_key: :component_id,
dependent: :destroy
end
component_controller.rb:
before_action :load_project
before_action :load_scope
def index
components = paginate #scope, per_page: per_page
data = ActiveModelSerializers::SerializableResource.new(
components,
each_serializer: ComponentSerializer
)
render_response(:ok, { data: data })
rescue ActiveRecord::RecordNotFound
render_response(:not_found, { resource: "Project/Lesson" })
end
def load_scope
#scope = #project.components
#scope = #scope.order("position")
end
def load_project
#project = Project.find(params[:project_id])
rescue ActiveRecord::RecordNotFound
render_response(:not_found, { resource: "Project/Lesson" })
end
I'm using Netflix's jsonapi-rails gem to serialize my API. I need to build a response.json object that includes the associated comments for a post.
Post model:
class Post < ApplicationRecord
has_many :comments, as: :commentable
end
Polymorphic Comment model
class Comment < ApplicationRecord
belongs_to :commentable, polymorphic: true
end
PostSerializer
class PostSerializer
include FastJsonapi::ObjectSerializer
attributes :body
has_many :comments, serializer: CommentSerializer, polymorphic: true
end
CommentSerializer
class CommentSerializer
include FastJsonapi::ObjectSerializer
attributes :body, :id, :created_at
belongs_to :post
end
Posts#index
class PostsController < ApplicationController
def index
#posts = Post.all
hash = PostSerializer.new(#posts).serialized_json
render json: hash
end
end
What I've got so far only gives me the comment type and id, but I NEED the comment's body as well.
Please help!
Thanks in advance~!
Although not very intuitive this behaviour is there by design. According to the JSON API relationship data and actual related resource data belong in different objects of the structure
You can read more here:
Fetching Relationships
Inclusion of Related Resources
To include the body of the Comments your serializers would have to be:
class PostSerializer
include FastJsonapi::ObjectSerializer
attributes :body, :created_at
has_many :comments
end
class CommentSerializer
include FastJsonapi::ObjectSerializer
attributes :body, :created_at
end
and your controller code:
class HomeController < ApplicationController
def index
#posts = Post.all
options = {include: [:comments]}
hash = PostSerializer.new(#posts, options).serialized_json
render json: hash
end
end
The response for a single Post would look something like this:
{
"data": [
{
"attributes": {
"body": "A test post!"
},
"id": "1",
"relationships": {
"comments": {
"data": [
{
"id": "1",
"type": "comment"
},
{
"id": "2",
"type": "comment"
}
]
}
},
"type": "post"
}
],
"included": [
{
"attributes": {
"body": "This is a comment 1 body!",
"created_at": "2018-05-06 22:41:53 UTC"
},
"id": "1",
"type": "comment"
},
{
"attributes": {
"body": "This is a comment 2 body!",
"created_at": "2018-05-06 22:41:59 UTC"
},
"id": "2",
"type": "comment"
}
]
}
I have many to many relation between projects and project_category through project_by_category.
My models:
Project Model
class Project < ApplicationRecord
# Relationships
has_many :project_by_categories
has_many :project_categories, through: :project_by_categories
ProjectCategory Model
class ProjectCategory < ApplicationRecord
has_many :project_by_categories
has_many :projects, through: :project_by_categories
ProjectByCategory Model
class ProjectByCategory < ApplicationRecord
# Relationships
belongs_to :project
belongs_to :project_category
My serializers:
Project Serializer
class ProjectSerializer < ActiveModel::Serializer
attributes :id, :image, :name, :description
Project Category Serializer
class ProjectCategorySerializer < ActiveModel::Serializer
attributes :id, :name
has_many :projects
The expected result:
{
"data": [
{
"id": "1",
"type": "project-categories",
"attributes": {
"name": "3D design basics"
},
"relationships": {
"projects": {
"data": [
{
"id": "1",
"image": "",
"name": "",
"description": "",
"type": "projects"
},
{
"id": "2",
"image": "",
"name": "",
"description": "",
"type": "projects"
}
]
}
}
},
But this is the result:
{
"data": [
{
"id": "1",
"type": "project-categories",
"attributes": {
"name": "3D design basics"
},
"relationships": {
"projects": {
"data": [
{
"id": "1",
"type": "projects"
},
{
"id": "2",
"type": "projects"
}
]
}
}
},
In the project relationship only show me the id and the type.
By last this is my controller
class Api::V1::CategoriesController < ApiController
def index
#categories = ProjectCategory.all
render json: #categories
end
Thank you for your answers!!
Your joins table appears to be setup correctly (and you seem to be grabbing the expected objects from your database), but you are just missing the additional serialized attributes.
Have you tried passing the serializer: or each_serializer: arguments to the respective serializer and controller? For example, your Api::V1::CategoriesController might look like this:
class Api::V1::CategoriesController < ApiController
def index
#categories = ProjectCategory.all
render json: #categories, each_serializer: ProjectCategorySerializer
end
end
Similarly, your ProjectCategorySerializer would contain:
class ProjectCategorySerializer < ActiveModel::Serializer
attributes :id, :name
has_many :projects, each_serializer: ProjectSerializer
I'm not sure if ActiveModel::Serializers are now a part of ActiveSupport, but the library seems to suggest that development has tapered off. I'd recommend switching a a different library if possible.
Hope this helps!
I have this models in ruby on rails
Branch model: has_many :menus
class Branch < ActiveRecord::Base
belongs_to :place
belongs_to :city
has_many :menus , dependent: :destroy
belongs_to :type_place
end
Menu model: has_many :products
class Menu < ActiveRecord::Base
attr_accessible :description, :product_name, :price, :category_id, :menu_id
belongs_to :branch
has_many :products, dependent: :destroy
end
Product model:
class Product < ActiveRecord::Base
belongs_to :menu
belongs_to :category
end
with the following code in the view:
if #condition
json.code :success
json.branch do
json.array!(#branches) do |json, branch|
json.(branch, :id, :branch_name, :barcode)
json.menu branch.menus, :id, :menu_name
end
end
else
json.code :error
json.message 'Mensaje de error'
end
gets:
{
"code": "success",
"branch": [
{
"id": 1,
"branch_name": "Sucursal 1",
"barcode": "zPOuByzEFe",
"menu": [
{
"id": 2,
"menu_name": "carta sucursal 1"
}
]
},
{
"id": 2,
"branch_name": "Sucursal Viña Centro",
"barcode": "RlwXjAVtfx",
"menu": [
{
"id": 1,
"menu_name": "carta viña centro"
},
{
"id": 5,
"menu_name": "carta viña centro vinos"
}
]
},
{
"id": 3,
"branch_name": "dddd",
"barcode": "eSbJqLbsyP",
"menu": [
]
}
]
}
But as I get the products of each menu?, I suspect I need to iterate menu, but I have tried several ways without success.
I'm not sure which attributes your product can have but i would try something like:
if #condition
json.code :success
json.array!(#branches) do |json, branch|
json.(branch, :id, :branch_name, :barcode)
json.menus branch.menus do |json,menue|
json.id menue.id
json.menu_name menue.menu_name
json.products menue.products do |json, product|
json.product_attribute_1 product.product_attribute_1
end
end
end
else
json.code :error
json.message 'Mensaje de error'
end
i'm also not quite sure why you try to nest #branches under a branch as stated by:
json.branch do
...
end
i just removed that.
This is from the docs ("this" is the "json.array! method) http://www.rubydoc.info/github/rails/jbuilder/Jbuilder:array!
It's generally only needed to use this method for top-level arrays. If
you have named arrays, you can do:
json.people(#people) do |person|
json.name person.name
json.age calculate_age(person.birthday)
end
{ "people": [ { "name": David", "age": 32 }, { "name": Jamie", "age": 31 } ] }
I had unexpected behaviors using array! and regular iteration as suggested worked perfectly and made my code very readable:
json.user do
json.email #user.email
json.devices #user.devices do |device|
json.partial! 'devices/device', device: device
end
end