Duy Huynh Duy Huynh - 1 year ago 81
MySQL Question

How to delete only the objects from ActiveRecord collection from mysql in Rails?

I am calculating weekly leaderboard stats for players of a game, using a service object I created. I am in a situation where if I want to redo the calculations for any particular week, I want to delete the old stats if and only if the new stats were saved successfully.

Roughly my steps:

  1. AR query existing stats for the given week into a variable

  2. Run that week's new stats

  3. Save the new data, returning if save was successful

  4. On success of saving new data, delete the objects from mysql of query in step 1.

I've tried using the
method but that will just run the query from the ActiveRecord_Relation object off of mysql at that moment, destroying the newly created data as well. I just want to destroy the ones I saved from the query I made before creating the new data.

Possible solution I haven't tried: Sorta hacky but flag the old data by updating an arbitrary column of all objects in the old data query with an arbitrary value and use
off of a query for that arbitrary value... This doesn't sound like the railsy way to do things and plus, it adds an extra query.

Answer Source

Instead of adding a flag, you could simply pluck the id's of the old rows, and then run a new query deleting those. The delete_all method by definition runs a new query, so there isn't a way to freeze the old results and delete those directly.

You might also try updating the rows directly if many of the fields (say player_id and game_id or something) are the same from week to week...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download