简体   繁体   English

如何在轨道上的 ruby 中解析嵌套的 hash 序列化?

[英]How to parsed serialize nested hash in ruby on rails?

I have order model which has one serialise column as order_details .我有order model 有一个序列化列作为order_details When I tries to call index action it returns the hash in order_details key.当我尝试调用索引操作时,它会在order_details键中返回 hash。

I want all the values of order_details in main object of order.我想要订单的主要 object 中的order_details的所有值。

My order model as below:我的订单 model 如下:

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

Controller 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:我收到的 JSON 响应如下:

[{
  "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.我试图使用each解析每个响应,但结果可能有数百个用户 object。

Please help here.请在这里帮忙。 Thanks in advance.提前致谢。

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您应该将as_json添加到您的 Order model 以覆盖具有相同名称的现有方法,以满足您的预期 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然后,在你的 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 FYR: https://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html#method-i-as_json

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM