Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
428 views
in Technique[技术] by (71.8m points)

Do rails rake tasks provide access to ActiveRecord models?

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.

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...