Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Why am I getting uninitialized Constant for a rake task, Rails 4.1.8

I have a problem when I do:

namespace :xaaron do   task :get_roles do     roles = Xaaron::Role.all     puts roles   end      task :get_role, [:name] do |t, args|     role = Xaaron::Role.find(args[:name].parameterize)     puts role   end end 

The first task will work fine. I can even add binding.pry and run Xaaron::Role and get information about Roles back. But the second task fails with:

NameError: uninitialized constant Xaaron::Role 

I run each task in my main app because these tasks are inside an engine, using:

bin/rake xaaron:get_roles` and `bin/rake xaaron:get_role 

I can run bin/rails c in the main application that uses the engine and run Xaaron::Role and get information about Roles table.

Why is the second one failing but the first one is not? Is there scoping with arguments?

like image 202
SeekingTruth Avatar asked Dec 11 '14 20:12

SeekingTruth


1 Answers

I'm not sure why either works, but if this is Rails and those are Rails models, your tasks should depend on the environment:

task :get_roles => [ :environment ] do 

By depending on the :environment task, it first loads Rails.

Also see: What's the 'environment' task in Rake?.

like image 79
DGM Avatar answered Oct 05 '22 16:10

DGM