使用rake任务更新记录

时间:2012-12-31 23:21:34

标签: ruby-on-rails cron rake

desc "This task is called by the Heroku scheduler add-on"
task :queue => :environment do
  puts "Updating feed..."
  @books = Book.all
  @books.update_queue
  puts "done."
end

我在lib / tasks中名为scheduler.rake的文件中有上述代码。当我运行rake queue时,我得到:

Updating feed...
rake aborted!
undefined method `update_queue' for #<Array:0x007ff07eb3ffd0>

该方法在我的Books模型中定义如下:

def update_queue
    days_gone = (Date.parse(:new_books.last.created_at.to_s) - Date.today).to_i

    unless days_gone > -7
        new_book = self.user.books.latest_first.new_books.last
        new_book.move_from_queue_to_reading
        user.books.reading_books.move_from_reading_to_list
    else
        self.user.books.create(:title => "Sample book", :reading => 1)
    end
  end

这只是没有访问书籍,这就是为什么它给我这个未定义的错误?我在这做错了什么?我只是想更新每本书的记录。

1 个答案:

答案 0 :(得分:2)

如错误消息所示,您无法在阵列上运行实例方法。 Book.all会返回books表中所有项目的数组。您需要循环遍历数组中的每个实例才能使其正常工作。您可以通过以下两种方式之一完成此任务。

使用标准块语法:

@books.each do |book|
  book.update_queue
end

或使用send method

Book.all.each.send(:update_queue)

无论哪种方式都应该完成同样的事情。