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

SeekingTruth picture SeekingTruth · Dec 11, 2014 · Viewed 13.3k times · Source

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.

Answer

DGM picture DGM · Dec 11, 2014

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?