使用Group_by获取每个对象的总数 - Rails

时间:2017-03-25 12:30:12

标签: ruby-on-rails ruby

这是一个棘手的问题,但我将尽可能具有描述性。我的应用有Events,他们有很多Purchases,他们有很多Tickets,他们有一个Ticket_type。我正在尝试获取在活动中购买的每个ticket_type的总数。我目前的尝试是按门票分组购买。这让我在某个地方,但我真的不知道从那里去哪里。这是我的代码

def ticket_type_purchases
  event.purchases.group_by(&:tickets)
end

The produces this:

{[#<Ticket:0x007fb43aacdf78 id: 400, attendee_id: 436, ticket_type_id: 29, purchase_id: 10>,
  #<Ticket:0x007fb43aacde38 id: 401, attendee_id: 437, ticket_type_id: 29, purchase_id: 10>]=>
  [#<Purchase:0x007fb431bb3388
    id: 10,
    coupon_id: nil,
    event_id: 51,
    discount: 0,
    stripe_transaction_id: "ch_1A0azuG8Z38E1yTozmbRtRKm",
    purchaser_email: "cam@example.com",
    fees: 307,
    rsvp_id: 412,
    subtotal: 2000,
    total: 2307>],
 [#<Ticket:0x007fb431edae80 id: 407, attendee_id: 443, ticket_type_id: 29, purchase_id: 11>,
  #<Ticket:0x007fb431edad40 id: 408, attendee_id: 444, ticket_type_id: 29, purchase_id: 11>,
  #<Ticket:0x007fb431edac00 id: 409, attendee_id: 445, ticket_type_id: 29, purchase_id: 11>]=>
  [#<Purchase:0x007fb431bb2bb8
    id: 11,
    coupon_id: nil,
    event_id: 51,
    discount: 0,
    stripe_transaction_id: "ch_1A0bg8G8Z38E1yTovTTvfne6",
    purchaser_email: "cam@example.com",
    fees: 461,
    rsvp_id: 415,
    subtotal: 3000,
    total: 3461>],
 [#<Ticket:0x007fb43a33b9e0 id: 415, attendee_id: 451, ticket_type_id: 29, purchase_id: 12>,
  #<Ticket:0x007fb43a33b8a0 id: 416, attendee_id: 452, ticket_type_id: 29, purchase_id: 12>,
  #<Ticket:0x007fb43a33b760 id: 417, attendee_id: 453, ticket_type_id: 29, purchase_id: 12>,
  #<Ticket:0x007fb43a33b620 id: 418, attendee_id: 454, ticket_type_id: 29, purchase_id: 12>,
  #<Ticket:0x007fb43a33b4e0 id: 419, attendee_id: 455, ticket_type_id: 29, purchase_id: 12>]=>
  [#<Purchase:0x007fb431bb23e8
    id: 12,
    coupon_id: nil,
    event_id: 51,
    discount: 0,
    stripe_transaction_id: "ch_1A0d9eG8Z38E1yTou7fffFOg",
    purchaser_email: "cam@example.com",
    fees: 768,
    rsvp_id: 417,
    subtotal: 5000,
    total: 5768>],
 [#<Ticket:0x007fb43a4db610 id: 423, attendee_id: 459, ticket_type_id: 33, purchase_id: 13>,
  #<Ticket:0x007fb43a4db4d0 id: 424, attendee_id: 460, ticket_type_id: 33, purchase_id: 13>,

模型:

事件:

 has_many :ticket_types, dependent: :destroy
 has_many :purchases, dependent: :destroy

购买:

belongs_to :event
has_many :tickets

Ticket_type:

 belongs_to :event

票:

 belongs_to :ticket_type
 belongs_to :purchase

所以,我每次购买都可以看到我有权访问ticket_type_id的票证的属性。回顾一下,我想获得在活动中购买的每个ticket_type的总计数。谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

尝试将此关联添加到Event

has_many :tickets, through: :purchases

这将有助于您获得event.tickets作为此活动的所有门票。

然后使用它来获取基于ticket_type的计数:

event.tickets.group(:ticket_type).count

这将返回一个哈希,其密钥为故障单类型,值为此事件中此故障单类型的故障单数量。

<强>更新 要使用ticket_id =&gt;获取哈希值数:

event.tickets.group(:ticket_type_id).count