Search code examples
ruby-on-railsrubygemsrake-task

Get current index value in Populator


I have created a rake task to create test data using populator. I need to read index of current iteration and set in one of the attribute of the model. Can anyone please tell how to read current index value in populate method?

namespace :db do
  desc "Erase and fill database"
  task :populate => :environment do
    require 'populator'

    Category.delete_all

    Category.populate 50 do |category|
      category.name = Populator.words(1..3).titleize
      category.index = {CURRENT_INDEX}
    end
  end
end

where {CURRENT_INDEX} should be index value of current iteration.

I tried adding index in block variable Category.populate 50 do |category, index| assuming ruby for each loop sysntax but didn't work.


Solution

  • Looks like rubygem.org has not updated gem after changes. Here is how I fixed it.

    I pointed source of gem directly to master branch.

    so replaced

    gem 'populator'
    

    with

    gem 'populator', git: "https://github.com/ryanb/populator.git"
    

    in Gemfile

    And in my rake task

    ...
    Category.populate 50 do |category, index|
          category.name = Populator.words(1..3).titleize
          category.index = index
        end
    ...