Including datetime helper rails in a custom rake task

I want to create a rake task to fill in the product details, but the product must be random in order to format the ability to sort later depending on the date. I would like to include the datehelper provided by the framework in it, but I have no idea about this. How can this be done. My custom rake task looks like this:

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 Cereal'", :price => 3.95, :released => 1.year.ago},
    {:name => "Red T-Shirt", :price => 12.49, :released => 2.years.ago},
    {:name => "Settler 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

But when I run the rake command for the task, it gives me an error like undefined method 'year' for 1:Fixnum, I assume that this error is due to the fact that it does not have access to the date helper methods provided by the rails. So how can I enable the assistant to enable support.

+3
source share
3 answers

: Rails :

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

, ...

+1

, , , lib autoload_paths application.rb

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

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

FYI, you saddened 5.moths.ago on the eighth line.

0
source

All Articles