SeekingTruth SeekingTruth - 1 year ago 71
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

task :get_role, [:name] do |t, args|
role = Xaaron::Role.find(args[:name].parameterize)
puts role

The first task will work perfectly fine. I can even place a
in side and do
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
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?


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

Answer Source

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?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download