ruby-on-railsjoinactiverecordpluck

Rails join pluck wrong id


This likely duplicate, but

BananaStand has_many :banana_sale_tickets
BananaSaleTicket belongs_to :banana_stand
BananaSaleTicket belongs_to :buyer
Buyer has_many :banana_sale_tickets
previous_banana_buyers_ids = @banana_stand.banana_sale_tickets.joins(:buyer).pluck(:id)

I'd like the ids of the buyers, but it's giving me the ids of the banana_sales_tickets.

Both have :id. Code works if I select another attribute that is unique to Buyer


Solution

  • You can try below:

    previous_banana_buyers_ids = @banana_stand.banana_sale_tickets.joins(:buyer).pluck('buyers.id').uniq
    

    Hope this helps.