2

I have a rails 4 app with a cron job that runs the following task once a day:

task :update_packs => :environment do
    @all_users = User.all

    @all_users.each do |user|
        today = where(:created_at => (Time.now.beginning_of_day..Time.now))
        @packs = user.default_packs
        if user.packs.today.count >= 1
            puts "ERROR: User already has a record today."
        else
            user.packs.create(:amount => @packs)
        end
    end
end

However, when I run the task, I get the following error:

NoMethodError: undefined method `where' for main:Object
/home/ben/rails_projects/hartwig/lib/tasks/packs.rake:7:in `block (2 levels) in <top (required)>'
/home/ben/.rvm/gems/ruby-2.1.1/gems/activerecord-4.1.0/lib/active_record/relation/delegation.rb:46:in `each'
/home/ben/.rvm/gems/ruby-2.1.1/gems/activerecord-4.1.0/lib/active_record/relation/delegation.rb:46:in `each'
/home/ben/rails_projects/hartwig/lib/tasks/packs.rake:6:in `block in <top (required)>'
/home/ben/.rvm/gems/ruby-2.1.1/bin/ruby_executable_hooks:15:in `eval'
/home/ben/.rvm/gems/ruby-2.1.1/bin/ruby_executable_hooks:15:in `<main>'
Tasks: TOP => update_packs

I've tried to replace where with conditions, but I get the same error. Any ideas?

zenben1126
  • 685
  • 1
  • 7
  • 25

2 Answers2

4

You need to call where on the class you're querying. (eg. User.where(...))

For example, to iterate over all the users created today, you'd do:

task :update_packs => :environment do
  User.where(:created_at => (Time.now.beginning_of_day..Time.now)).each do |user|
    ...
  end
end
Sam Starling
  • 5,298
  • 3
  • 35
  • 52
4

Write your loop like this:

@all_users.each do |user|
  @packs = user.default_packs
  if user.packs.where(:created_at => (Time.now.beginning_of_day..Time.now).exists?
    puts "ERROR: User already has a record today."
  else
    user.packs.create(:amount => @packs)
  end
end

I would however strongly suggest adding a scope to your Pack model:

class Pack < ActiveRecord::Base
  scope :today, -> { where(:created_at => (Time.now.beginning_of_day..Time.now)) }
end

Then your task would look like:

  @all_users.each do |user|
  @packs = user.default_packs
  if user.packs.today.exists?
    puts "ERROR: User already has a record today."
  else
    user.packs.create(:amount => @packs)
  end
end
BroiSatse
  • 44,031
  • 8
  • 61
  • 86