0

i am trying to run a rake task to add to my database. However i am getting the error below. If anybody has had this error or knows the solution, any help would be greatly appreciated!


rails aborted!
NameError: uninitialized constant User
/Users/richardbatt/Desktop/Ruby/NelsonParksProject/lib/tasks/users.rake:31:in `block (3 levels) in <main>'
/Users/richardbatt/Desktop/Ruby/NelsonParksProject/lib/tasks/users.rake:22:in `each'
/Users/richardbatt/Desktop/Ruby/NelsonParksProject/lib/tasks/users.rake:22:in `block (2 levels) in <main>'
/Users/richardbatt/Desktop/Ruby/NelsonParksProject/bin/rails:4:in `<main>'
Tasks: TOP => users:xero_users
(See full trace by running task with --trace)

namespace :users do
  desc "Gets Users from Xero"
  task :xero_users do

    require 'xero-ruby'

    creds = {
      client_id: '...',
      client_secret: '...',
      grant_type: 'client_credentials'
    }

    xero_client = XeroRuby::ApiClient.new(credentials: creds)

    @token_set = xero_client.get_client_credentials_token
    # save @token_set

    accessToken = @token_set["access_token"]

    users = xero_client.accounting_api.get_users('').users

    users.each do |user|

      userID = user.user_id
      userEmailAddress = user.email_address
      userFirstName = user.first_name
      userLastName = user.last_name
      userIsSubscriber = user.is_subscriber
      userOrganisationRole = user.organisation_role

      User.create(email: userEmailAddress)

    end

  end
end

I was trying to add the new user to my database. When i use 'User.create(email: "test")' in my home controller it adds to the database. Just not when i run the rake task.

Thank You!

1 Answers1

3

Rake tasks do not automatically load the Ruby on Rails environment.

When you want to use Rails models in your Rake tasks, then you have to tell Ruby to load the Rails environment by changing this line

task :xero_users do

to

task xero_users: :environment do
spickermann
  • 100,941
  • 9
  • 101
  • 131