【问题标题】:Update records using rake task使用 rake 任务更新记录
【发布时间】:2012-12-31 23:21:34
【问题描述】:
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

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

【问题讨论】:

    标签: ruby-on-rails cron rake


    【解决方案1】:

    正如错误消息所述,您不能在数组上运行实例方法。 Book.all 返回 books 表中所有项目的数组。您需要遍历数组中的每个实例才能使其工作。您可以通过以下两种方式之一来执行此操作。

    使用标准块语法:

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

    或使用send method

    Book.all.each.send(:update_queue)
    

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

    【讨论】:

    • 啊,好吧,我明白了。所以我像你的第一个代码块一样遍历它们,然后它告诉我“最后一个”是未定义的。 days_gone = (Date.parse(:new_books.last.created_at.to_s) - Date.today).to_i 有没有更好的方法来使用其他东西来获取最新的而不是'last'?
    • :new_books 符号从何而来? last 是一个数组方法,显然:new_books 不是一个数组。如果:new_books 应该是存储该数组的变量,则不应使用符号作为变量名。
    • :new_books 是一个作用域方法。 scope :new_books, lambda {|created_date| {:conditions =&gt; "created_at &gt; '#{created_date}'"} }
    • 作用域是在类上调用的简单方法,guides.rubyonrails.org/active_record_querying.html#scopes。因此,您应该致电Book.new_books.last
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-03
    • 1970-01-01
    • 2013-09-14
    • 2011-01-15
    • 1970-01-01
    相关资源
    最近更新 更多