0

I have this array:

[[#<Ticket:0x007f993e368538 id: 400, attendee_id: 436, ticket_type_id: 29, purchase_id: 10>, #<Ticket:0x007f993e3683f8 id: 401, attendee_id: 437, ticket_type_id: 29, purchase_id: 10>], [#<Ticket:0x007f993e56af20 id: 407, attendee_id: 443, ticket_type_id: 29, purchase_id: 11>, #<Ticket:0x007f993e56ade0 id: 408, attendee_id: 444, ticket_type_id: 29, purchase_id: 11>, #<Ticket:0x007f993e56aca0 id: 409, attendee_id: 445, ticket_type_id: 29, purchase_id: 11>], [#<Ticket:0x007f993dc7db60 id: 415, attendee_id: 451, ticket_type_id: 29, purchase_id: 12>, #<Ticket:0x007f993dc7da20 id: 416, attendee_id: 452, ticket_type_id: 29, purchase_id: 12>, #<Ticket:0x007f993dc7d8e0 id: 417, attendee_id: 453, ticket_type_id: 29, purchase_id: 12>, #<Ticket:0x007f993dc7d7a0 id: 418, attendee_id: 454, ticket_type_id: 29, purchase_id: 12>, #<Ticket:0x007f993dc7d660 id: 419, attendee_id: 455, ticket_type_id: 29, purchase_id: 12>], [#<Ticket:0x007f993dde8c98 id: 423, attendee_id: 459, ticket_type_id: 33, purchase_id: 13>, #<Ticket:0x007f993dde8ae0 id: 424, attendee_id: 460, ticket_type_id: 33, purchase_id: 13>, #<Ticket:0x007f993dde89a0 id: 425, attendee_id: 461, ticket_type_id: 33, purchase_id: 13>]] 

I got it with this code: event.purchases.collect(&:tickets)

Now that I have that array I want to get an array of just the ticket_type_id value. so it should look like this [29, 29, 29, 29, 29, 29, 29, 29, 33, 33, 33]

Hopefully that is enough information.

2 Answers 2

3

Try this one

event.purchases.flat_map(&:tickets).map(&:ticket_type_id) 

map is like collect

But it's possible do everything in SQL that is often better. Something like this should work

Ticket.joins(:purchase).where(purchases: { event_id: event.id }).pluck(:ticket_type_id) 
Sign up to request clarification or add additional context in comments.

2 Comments

using pluck instead of select (if it is Rails) allows you get an array without model creating (it's faster and consuming less memory)
@Ursus Thank you for the help! This is a part of a bigger problem I'd love your help here: stackoverflow.com/questions/43017308/… Thanks man
2

As mentioned in another related question of yours, if you add an association in Event:

has_many :tickets, through: :purchases 

It would look cleaner to just get event.tickets which are all the tickets of purchases belonging to this event.

Else, map is the solution as Ursus replied.

1 Comment

Thanks for all the help this is a part of a bigger problem. I posted another question at stackoverflow.com/questions/43017308/… I'd love your help on it Thank You!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.