开发者

Rails 2.3.9 - scope, delete_all, update_all

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, :condit开发者_JAVA百科ions => ["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:

#Your RaceWeek Model
class RaceWeek < ActiveRecord::Base

named_scope :started_before_and_ended_after_today, :conditions => ["start_date <= #{Time.now} AND end_date >= #{Time.now}"]

named_scope :not_recordable_user, :conditions => ["recordable_type != 'User'"]

end

Now in any of your controllers, instead of having to write out something like this each time:

RaceWeek.find(:all, :conditions => ["start_date <= #{Time.now} AND end_date >= #{Time.now} AND recordable_type != 'User'"])

You can just write something much cleaner like this:

RaceWeek.started_before_and_ended_after_today.not_recordable_user.find(:all)

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:

#Your RaceWeek Model
class RaceWeek < ActiveRecord::Base

named_scope :started_before_and_ended_after_today, :conditions => ["start_date <= #{Time.now} AND end_date >= #{Time.now}"]

named_scope :not_recordable_user, :conditions => ["recordable_type != 'User'"]

def self.reset_records
  started_before_and_ended_after_today.not_recordable_user.delete_all   
  started_before_and_ended_after_today.each { |record| record.update_attributes(:games_won => 0, :games_lost => 0)}      
end

end

Now whenever you need to delete everything and update only the remaining records that are left. All you need to do is call:

RaceWeek.reset_records
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜