我有一个Customers
表和一个Orders
表。每个客户都有多个订单。当我做Customers.all.as_json(:include => :orders)
时,我得到所有订单,但我只是想得到计数
我尝试了Customers.all.as_json(:include => {:orders => {:only => [], :methods => [:custom_method_to_get_order_count}})
虽然它获得了正确的计数,但我有一个对象数组,它等于count。
输出错误! :(
[
{
:customer_id => 1,
:customer_name => "ABC",
:orders => [
{:custom_method_to_get_order_count => 2},
{:custom_method_to_get_order_count => 2}
]
},
{
:customer_id => 2,
:customer_name => "DEF",
:orders => [
{:custom_method_to_get_order_count => 3},
{:custom_method_to_get_order_count => 3},
{:custom_method_to_get_order_count => 3}
]
},
{
:customer_id => 3,
:customer_name => "XYZ",
:orders => [
{:custom_method_to_get_order_count => 10},
{:custom_method_to_get_order_count => 10},
{:custom_method_to_get_order_count => 10},
{:custom_method_to_get_order_count => 10},
{:custom_method_to_get_order_count => 10},
{:custom_method_to_get_order_count => 10},
{:custom_method_to_get_order_count => 10},
{:custom_method_to_get_order_count => 10},
{:custom_method_to_get_order_count => 10},
{:custom_method_to_get_order_count => 10}
]
}
]
正在寻找正确的输出
[
{
:customer_id => 1,
:customer_name => "ABC",
:orders => {
:custom_method_to_get_order_count => 2
}
},
{
:customer_id => 2,
:customer_name => "DEF",
:orders => {
:custom_method_to_get_order_count => 3
}
},
{
:customer_id => 3,
:customer_name => "XYZ",
:orders => {
:custom_method_to_get_order_count => 10
}
}
]
答案 0 :(得分:2)
你也可以这样使用:
class Customers
def get_orders_count
self.orders.count
end
end
现在您可以在客户对象中获得所有订单数:
Customers.all.as_json(method: :get_orders_count)
输出类似于:
[
{
:customer_id => 1,
:customer_name => "ABC",
:get_orders_count => 12
},
{
:customer_id => 2,
:customer_name => "DEF",
:get_orders_count => 20
},
{
:customer_id => 3,
:customer_name => "XYZ",
:get_orders_count => 50
}
]
答案 1 :(得分:0)
class Customers
def custom_method_to_get_order_count
Orders.where(:customer_id => id).count
end
end
发生了什么事,每当我在SO上发布问题时,我都会得到答案!