Custom rake task not finding a model

6 views
Skip to first unread message

Sebastjan Hribar

unread,
Dec 4, 2024, 3:50:42 PM12/4/24
to Roda
Hi,

I've added a custom rake task at the end of the migrate section in Rakefile.

desc "Creates an admin if one doesn't exist. Use: bundle exec rake admin:create"
task :create_admin do
puts "Creating admin user..."
@admin = User.first(role: "admin")

if !@admin
name = ENV["ADMIN_NAME"]
surname = ENV["ADMIN_SURNAME"]
username = ENV["ADMIN_USERNAME"]
email = ENV["ADMIN_EMAIL"]
password = ENV["ADMIN_PASSWORD"]
user_password = Argon2::Password.create(password)
@admin = User.new(name: name, surname: surname, username: username, email: email, role: "admin", hashed_pass: user_password, active_status: true)
puts "Admin #{@admin.name} #{@admin.surname} was created."
else
puts "Admin already exists. Contact the app owner."
end
end

The problem is that I get the Uninitialized constant User error. If migrations run ok, shouldn't this task also?

seba

Jeremy Evans

unread,
Dec 4, 2024, 6:03:15 PM12/4/24
to ruby...@googlegroups.com
It doesn't look like you are loading the User model, unless you are doing that in the Rakefile itself.  Maybe you need to add:

  require  './models'

to the top of the task, or something similar to ensure the class is loaded?

Thanks,
Jeremy
Reply all
Reply to author
Forward
0 new messages