Move records from an array of records if matched id

Viewed 33

Using Rails 6.

My dirty code

      active_card_ids = JSON.parse(cookies[:card_ids])
      @active_cards = []

      @best_cards = Houses.where("#{payment_category} IS NOT NULL").order("#{payment_category} DESC")
      @best_cards.each do |card|
        if active_card_ids.include? card.id
          @active_cards << card
        end
      end

What I am trying to do

I have an array of records queried: queried_records = [<object id: 1>, <object id: 3>, <object id: 4>, <object id: 7>]

Another array of IDs: wanted_ids = [4, 5]

Create another array: selected_records = []

I want to move queried_records found in wanted_ids, to selected_records.

In this example, we found <object id: 4> from queried_records, so we want to move (not copy) it to selected_records.

The results should be selected_records return an array [<object id: 4>]

1 Answers

If I understood your problem correctly, there will be id's in active_card_ids and you want another array with those id's only.

You can try querying the DB directly, then you don't have to run the loop.

The below sample takes an array of id's and passes it to where IN clause to query only active cards.

active_card_ids = JSON.parse(cookies[:card_ids])
@active_cards = Houses.where(id: active_card_ids).where("#{payment_category} IS NOT NULL").order("#{payment_category} DESC")
@best_cards = Houses.where("#{payment_category} IS NOT NULL").order("#{payment_category} DESC")
 

Another approach you can try is:

active_card_ids = JSON.parse(cookies[:card_ids])
@best_cards = Houses.where("#{payment_category} IS NOT NULL").order("#{payment_category} DESC")
@active_cards = @best_cards.select{ |card| active_card_ids.include? card.id }
Related