I have a model called RaceWeek. Two operations I want to perform:
(1) I want to scope-down the records using this condition:
"start_date <= #{Time.now} AND end_date >= #{Time.now} AND recordable_type != 'User'"
Then I want to delete all those records. Here’s how I am trying to now:
RaceWeek.delete_all("start_date <= #{Time.now} AND end_date >= #{Time.now} AND recordable_type != 'User'")
(2) After I delete all those, I then want to reset values for the remaining records. Here’s how I am trying to do that now:
RaceWeek.find(:all, :conditions => ["start_date <= #{Time.now} AND end_date >= #{Time.now}"]).update_all("games_won = 0, games_lost = 0")
Without going into all the issues that I’m running into, can you explain how you typically execute these type of operations?
I think I see what you’re trying to do.. But I think there’s better ways you could approach it. I’m not sure of the context of what you’re doing so you may can replace the following named_scope names with something more appropriate, but if you have something like this:
Now in any of your controllers, instead of having to write out something like this each time:
You can just write something much cleaner like this:
So now you can chain named_scopes together whenever you like. But it looks like you’re trying to do something reasonably repetitive so rather than having to write that out every time in every controller you want to use it in you should just create a “class method” on your RaceWeek model to do it for you. The following model can be refractored down a lot more as well but hopefully this will get you started:
Now whenever you need to delete everything and update only the remaining records that are left. All you need to do is call: