NoMethodError:未定义的方法`where' for main:Object(rake task) - Rails 4

时间:2014-06-04 15:04:39

标签: ruby-on-rails ruby rake where

我有一个带有cron作业的rails 4 app,每天运行一次以下任务:

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

但是,当我运行任务时,我收到以下错误:

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

我尝试用条件替换 where ,但是我得到了同样的错误。有任何想法吗?

2 个答案:

答案 0 :(得分:4)

您需要在您查询的课程上致电where。 (例如User.where(...)

例如,要迭代今天创建的所有用户,您需要:

task :update_packs => :environment do
  User.where(:created_at => (Time.now.beginning_of_day..Time.now)).each do |user|
    ...
  end
end

答案 1 :(得分:4)

像这样写你的循环:

@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

但我强烈建议您在Pack模型中添加范围:

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

然后你的任务看起来像:

  @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
相关问题