SeekingTruth SeekingTruth - 3 months ago 9
Ruby Question

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

I have this strange issue where if 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 perfectly fine. I can even place a
binding.pry
in side and do
Xaaron::Role
and get information about Roles back. But the second task explodes stating
NameError: uninitialized constant Xaaron::Role


I run each task, in my main app (as these tasks are inside a engine) as:
bin/rake xaaron:get_roles
and
bin/rake xaaron:get_role
.

Why is the second one exploding but the first one is not? Is there a scoping thing that goes on with arguments?

Update

I should note that I can do a
bin/rails c
in the main app that uses said engine and do
Xaaron::Role
and get information about Roles table.

DGM DGM
Answer

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.

see also:

What's the 'environment' task in Rake?