我有以下代码
def self.activate_lessons
i = 0
#for lesson in Lesson.to_activate
for lesson in Lesson.find :all, :conditions => ["start_date < ? AND (active <> ? OR active IS NULL)", DateTime.now, true]
lesson.active = true
lesson.save
i += 1
end
i
end
这是一个vaild rails 4.2代码吗?
我收到了这个错误:
ActiveRecord::RecordNotFound: Couldn't find all Lessons with 'id': (all, {:conditions=>["start_date < ? AND (active <> ? OR active IS NULL)", Sat, 02 Apr 2016 09:50:06 +0000, true]}) (found 0 results, but was looking for 2)
答案 0 :(得分:2)
如果您的目标是激活课程并返回已激活的课程数量,您可以这样做
def self.activate_lessons
Lesson.where.not(active: true).where("start_date < ?", DateTime.now).update_all(active: true)
end
find(:first)和find(:all)支持从rails 3.2 +。
中删除
答案 1 :(得分:1)
尝试使用此代码:
Lesson.where("start_date < ? AND active = ?", DateTime.now,Nil).update_all(active: true)