manis
manis

Reputation: 729

How to "shift" objects from ActiveRecord array

I have this method

def gen_events(score)
  events = location.events
  (1..rand(5..7)).each do |n|
    random = rand(0.139..1).round(3)
    rarity = Character.get_rarity(random)
    event = events.where(rarity: rarity).shuffle.shift #<-- HERE
    self.events << event    
  end
end

Currently, the shift method only grabs the first element, but doesn't remove it, how can I go about making it so that it does both?

Upvotes: 2

Views: 2683

Answers (1)

BroiSatse
BroiSatse

Reputation: 44715

This is not an array: events.where(rarity: rarity), this is an ActiveRecord scope, you can't remove things from it without destroying and erasing them from database. Instead, you should keep an array of object you already found, and use it to filter future results:

def gen_events(score)
    events = location.events
    new_events = []
    (1..rand(5..7)).each do |n|
        random = rand(0.139..1).round(3)
        rarity = Character.get_rarity(random)
        event = events.where(rarity: rarity).where.not(id: new_events.map(&:id).sample
        new_events << event
    end
    self.events << new_events    
end

Upvotes: 2

Related Questions