简体   繁体   English

Rails Rake任务错误消失,而控制台等效项却没有

[英]Rails Rake task errors out while console equivalent does not

I have a piece of code that works fine in the console, but in a cron-driven rake task, it errors out every time, saying that the accessor function for one of the has_many relationships is not a valid method. 我有一段代码在控制台中可以正常工作,但是在cron驱动的rake任务中,它每次都会出错,并说has_many关系之一的访问器函数不是有效的方法。 Example: 例:

provider has_many instances, so I'm calling provider.instances, and the rake task will throw back an error: provider has_many实例,因此我在调用provider.instances,并且rake任务将抛出错误:

"undefined method `instances' for "#<Provider:0x7fff1c18a5d8>":Provider"

In the console, the same function pasted in works fine. 在控制台中,粘贴的相同功能可以正常工作。

The rake call: 抽佣电话:

rake RAILS_ENV=production scheduled:update_recurring --trace

The console initialization: 控制台初始化:

script/console production

Rails version 2.3.2 Rails版本2.3.2

See anything obvious? 看到明显的东西吗?

UPDATE: The rake file is setup as so: 更新:rake文件设置如下:

namespace :scheduled do
    task :update_recurring => :environment do
        Stuff that worked in console but not rake here
    end
end

In your console, the rails environment is loaded for you. 在您的控制台中,已为您加载了rails环境。

I am hoping that you have loaded the rails environment when you created the rails task. 我希望您在创建rails任务时已经加载了rails环境。

Update 更新资料

"RAILS_ENV=production" “ RAILS_ENV =生产”

just specifies the that which environment you are using thats all,so you can use it with "ENV["RAILS_ENV"]" inside your code. 只需指定您正在使用的环境即可,因此您可以在代码内部将其与“ ENV [“ RAILS_ENV”]“一起使用。

to load rails you need to do this. 要加载导轨,您需要执行此操作。

require File.dirname(__FILE__) + "/../config/environment"

Did you tell rake that your task is dependent on loading the Rails environment? 您是否告诉rake您的任务取决于加载Rails环境?

namespace :scheduled do
 task :update_recurring => :environment do
   ...
 end 
end

I had this exact same problem. 我有这个完全相同的问题。 The only way I could get it to work was to reload the class that caused the error. 我可以使它起作用的唯一方法是重新加载导致错误的类。

task :my_task => :environment do
  load "#{Rails.root}/app/models/my_class.rb" # Needed to do this

  foo = MyClass.create(my_attr: 'bar') # my_attr will be nil (huh??) unless I load the class
  foo.items.create(...) # This is the has_many that failed before loading the class
end

It's like the class loader loaded the class name, but it didn't get any of the definition. 就像类加载器加载了类名一样,但是没有得到任何定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM