Rails 2.3.9 - scope,delete_all,update_all

时间:2011-05-14 23:09:13

标签: mysql ruby-on-rails scope

我有一个名为RaceWeek的模型。我想要执行的两个操作:

(1)我想使用以下条件对记录进行范围缩小:

"start_date <= #{Time.now} AND end_date >= #{Time.now} AND recordable_type != 'User'"

然后我要删除所有这些记录。以下是我现在的尝试:

RaceWeek.delete_all("start_date <= #{Time.now} AND end_date >= #{Time.now} AND recordable_type != 'User'")

(2)删除所有这些后,我想重置其余记录的值。以下是我现在尝试这样做的方法:

RaceWeek.find(:all, :conditions => ["start_date <= #{Time.now} AND end_date >= #{Time.now}"]).update_all("games_won = 0, games_lost = 0")

如果不解决我遇到的所有问题,您能解释一下您通常如何执行这些类型的操作吗?

1 个答案:

答案 0 :(得分:0)

我想我看到你要做的事情......但我认为你有更好的方法可以接近它。我不确定你正在做什么的上下文所以你可以用更合适的东西替换下面的named_scope名称,但如果你有这样的东西:

#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

现在在任何一个控制器中,不必每次都写出类似的内容:

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

你可以写一些更清洁的东西:

RaceWeek.started_before_and_ended_after_today.not_recordable_user.find(:all)

所以现在你可以随时链接named_scopes。但是看起来你正在尝试做一些合理重复的事情,而不是每次都想在你想要使用它的每个控制器中写出来,你应该在你的RaceWeek模型上创建一个“类方法”来为你做。以下模型可以进行更多折射,但希望这可以帮助您开始:

#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

现在,只要您需要删除所有内容并仅更新剩余的剩余记录。您需要做的就是致电:

RaceWeek.reset_records