3

我想创建一个 rake 任务来填充产品的详细信息,但产品必须是随机的,以便格式化能够稍后根据日期对其进行排序。我想在其中包含框架提供的 datehelper,但我似乎对此一无所知。如何才能做到这一点。我的自定义 rake 任务如下所示;

namespace :db do
desc "Filling the data with  products"
  task :fill_products do 
    [{:name => "1 Galon milk", :price => 2.99, :released => Time.now.to_datetime},
    {:name => "Oh's Cereal'", :price => 3.95, :released => 1.year.ago},
    {:name => "Red T-Shirt", :price => 12.49, :released => 2.years.ago},
    {:name => "Settler's of Catan'", :price => 29.95, :released => 2.months.ago},
    {:name => "Video Game Disc", :price => 29.95, :released => 5.moths.ago},
    {:name => "DVD Player", :price => 79.99, :released => 88.days.ago},
    {:name => "Oak Coffee Table", :price => 223.99, :released => 499.days.ago},
    {:name => "Video Game Console", :price => 299.95, :released => 982.days.ago},
    {:name => "Black Leather Couch", :price => 399.99, :released => 1092.days.ago}
    ].each do |attr|
      Product.create!(attr)
    end
  end
end

但是当我为任务运行 rake 命令时,它给了我错误undefined method 'year' for 1:Fixnum,我想这个错误是由于它无法访问 rails 提供的日期帮助器方法。那么如何包含帮助程序以启用支持。

4

3 回答 3

1

尝试使您的任务依赖于 :environment Rails 的任务:

task :fill_products => :environment do
  # ...
end

让我们看看会发生什么...

于 2012-05-20T17:26:57.830 回答
1

仅供参考,您在第 8 行拼错了 5.moths.ago。

于 2015-01-13T22:47:25.757 回答
0

试试吧,我想它会工作的,首先在你的application.rb中的autoload_paths中添加lib文件

config.autoload_paths += %W(#{config.root}/lib)

然后做以下事情

task :fill_products => :environment do
     # ...
end
于 2012-05-26T18:28:16.583 回答