【问题标题】:NoMethodError: undefined method `where' for main:Object (rake task) - Rails 4NoMethodError:main:Object(rake任务)的未定义方法“where” - Rails 4
【发布时间】:2014-06-04 15:04:39
【问题描述】:

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

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 替换为 conditions,但我得到了同样的错误。有任何想法吗?

【问题讨论】:

    标签: ruby-on-rails ruby rake where


    【解决方案1】:

    这样写你的循环:

    @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
    

    【讨论】:

      【解决方案2】:

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

      例如,要遍历今天创建的所有用户,您应该这样做:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-07-14
        • 1970-01-01
        • 1970-01-01
        • 2012-12-28
        • 2016-07-30
        • 1970-01-01
        • 2011-09-07
        相关资源
        最近更新 更多