How to parsed serialize nested hash in ruby on rails?

Viewed 24

I have order model which has one serialise column as order_details. When I tries to call index action it returns the hash in order_details key.

I want all the values of order_details in main object of order.

My order model as below:

# models/order.rb
class Order < ActiveRecord::Base
  belongs_to :user
  serialize :order_details
  ....
end

Controller

# controllers/orders_controller.rb
class OrdersController < ApplicationController
  def index
    orders = Order.select('id, user_id, total, order_details')
    render json: orders, status: :ok
  end
end

The JSON response I received is as below:

[{
  "order":{
    "id":1,
    "user_id":1,
    "total": 1000,
    "order_details":{
      "payment_done_by":"credit/debit",
      "transaction_id":"QWERTY12345",
      "discount":210,
      "shipping_address": "This is my sample address"
    }
  },
  {
  "order":{
    "id":2,
    "user_id":2,
    "total": 500,
    "order_details":{
    "payment_done_by":"net banking",
    "transaction_id":"12345QWERTY",
    "discount":100,
    "shipping_address": "This is my sample address 2"
    }
  }
] 

But here I need response in below format

[{
  "order":{
    "id":1,
    "user_id":1,
    "total": 1000,
    "payment_done_by":"credit/debit",
    "transaction_id":"QWERTY12345",
    "discount":210,
    "shipping_address": "This is my sample address"
  },
  {
  "order":{
    "id":2,
    "user_id":2,
    "total": 500,
    "payment_done_by":"net banking",
    "transaction_id":"12345QWERTY",
    "discount":100,
    "shipping_address": "This is my sample address 2"
  }
]

I was trying to parsed each response using each but result can have hundreds of user object.

Please help here. Thanks in advance.

1 Answers

Krishna

you should add as_json to your Order model to override the existing method with the same name for you to meet your expected output

def as_json(options = nil)
  if options.blank? || options&.dig(:custom)
    attrs = attributes.slice("id", "user_id", "total")
    attrs.merge(order_details)
  else
    super
  end
end

then, in your controller

def index
  orders = Order.all
  render json: orders, status: :ok
end

hope that helps

FYR: https://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html#method-i-as_json

Related