不要轨Rake任务提供访问ActiveRecord模型?模型、任务、Rake、ActiveRecord

2023-09-09 21:58:28 作者:刚下凡不久

我想创建一个自定义的rake任务,但似乎我没有访问我的模型。我认为这是一些隐含有轨任务。

I am trying to create a custom rake task, but it seems I dont have access to my models. I thought this was something implicitly included with rails task.

我在的lib /任务/ test.rake以下code:

I have the following code in lib/tasks/test.rake:

namespace :test do
  task :new_task do
    puts Parent.all.inspect
  end
end

和这里是我的父模型是这样的:

And here is what my parent model looks like:

class Parent < ActiveRecord::Base
  has_many :children
end

这是一个pretty的简单的例子,但我得到了以下错误:

It's a pretty simple example, but I get the following error:

/> rake test:new_task
(in /Users/arash/Documents/dev/soft_deletes)
rake aborted!
uninitialized constant Parent

(See full trace by running task with --trace)

任何想法?谢谢

Any ideas? Thanks

推荐答案

想通了,任务应该是这样的:

Figured it out, the task should look like:

namespace :test do
  task :new_task => :environment do
    puts Parent.all.inspect
  end
end

请注意,'=>:环境的依赖添加到任务

Notice the '=> :environment' dependency added to the task