如何在ruby on rails中解析序列化嵌套哈希



我有一个order模型,它有一个串行列作为order_details。当我尝试调用索引操作时,它会返回order_details密钥中的散列。

我希望order_details的所有值都在主对象中。

我的订单型号如下:

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

控制器

# 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

我收到的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"
}
}
] 

但在这里,我需要以下格式的响应

[{
"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"
}
]

我试图使用each解析每个响应,但结果可能有数百个用户对象。

请在这里帮忙。提前谢谢。

Krishna

您应该将as_json添加到您的订单模型中,以覆盖具有相同名称的现有方法,从而满足您的预期输出

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

然后,在您的控制器中

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

希望能帮助

财政年度:https://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html#method-i-as_json

最新更新