rake aborted! for uninitialized constant that does exist - ruby-on-rails

I have built a rake task --
# SET RAKE TASK NAMESPACE
namespace :db do
# RAKE TASK DESCRIPTION
desc "Fetch property information and insert it into the database"
# RAKE TASK NAME
task :insert_properties do
# REQUIRE LIBRARIES
require 'nokogiri'
require 'open-uri'
# OPEN THE XML FILE
mits_feed = File.open("app/assets/xml/mits.xml")
# OUTPUT THE XML DOCUMENT
doc = Nokogiri::XML(mits_feed)
# FIND PROPERTIES OWNED BY NORTHSTEPPE AND CYCLE THORUGH THEM
doc.xpath("//Property/PropertyID/Identification[#OrganizationName='northsteppe']").each do |property|
# GATHER EACH PROPERTY'S INFORMATION
information = {
"street_address" => property.xpath("/Address/AddressLine1/text()"),
"city" => property.xpath("/Address/City/text()"),
"zipcode" => property.xpath("/Address/PostalCode/text()"),
"short_description" => property.xpath("/Information/ShortDescription/text()"),
"long_description" => property.xpath("Information/LongDescription/text()"),
"rent" => property.xpath("/Information/Rents/StandardRent/text()"),
"application_fee" => property.xpath("/Fee/ApplicationFee/text()"),
"bedrooms" => property.xpath("/Floorplan/Room[#RoomType='Bedroom']/Count/text()"),
"bathrooms" => property.xpath("/Floorplan/Room[#RoomType='Bathroom']/Count/text()"),
"bathrooms" => property.xpath("/ILS_Unit/Availability/VacancyClass/text()")
}
# CREATE NEW PROPERTY WITH INFORMATION HASH CREATED ABOVE
Property.create!(information)
end # ENDS XPATH EACH LOOP
end # ENDS INSERT_PROPERTIES RAKE TASK
end # ENDS NAMESAPCE DECLARATION
when I run "rake db:insert_properties" this is the error I produce --
rake aborted!
uninitialized constant Property
/Users/stevejobs/Sites/nsrosu/lib/tasks/property_information.rake:39:in `block (3 levels) in <top (required)>'
/Library/Ruby/Gems/2.0.0/gems/nokogiri-1.6.1/lib/nokogiri/xml/node_set.rb:237:in `block in each'
/Library/Ruby/Gems/2.0.0/gems/nokogiri-1.6.1/lib/nokogiri/xml/node_set.rb:236:in `upto'
/Library/Ruby/Gems/2.0.0/gems/nokogiri-1.6.1/lib/nokogiri/xml/node_set.rb:236:in `each'
/Users/stevejobs/Sites/nsrosu/lib/tasks/property_information.rake:21:in `block (2 levels) in <top (required)>'
Tasks: TOP => db:insert_properties
(See full trace by running task with --trace)
I have a Property model with a table set up to accept all of these attributes, so why am I getting this error?

Your rake task needs to boot the Rails environment prior to running. That way you can access the classes.
To do this, you need to run the environment task. To make this happen, change your task definition to
task :insert_properties => :environment do

Related

Rails Tenant schema switching with background jobs not working

Setting up a scheduled rake task using Whenever gem.
Required to switch to a specific schema (Using Apartment gem in my project)
Code in config/schedule.rb
env :PATH, ENV['PATH']
env :GEM_PATH, ENV['GEM_PATH']
set :output, "#{Whenever.path}/log/scheduler.log"
every 1.minute do
rake "db:my_task"
end
Code in lib/tasks/my_task.rake
namespace :db do
task :my_task => :environment do
Apartment::Tenant.switch("subdomain") do
#My Code here
end
end
end
Produces the following error in logs log/scheduler.logs
rake aborted!
Apartment::TenantNotFound: One of the following schema(s) is invalid: "subdomain" "public"
/var/lib/gems/2.3.0/gems/apartment-1.2.0/lib/apartment/adapters/postgresql_adapter.rb:72:in `rescue in connect_to_new'
/var/lib/gems/2.3.0/gems/apartment-1.2.0/lib/apartment/adapters/postgresql_adapter.rb:65:in `connect_to_new'
/var/lib/gems/2.3.0/gems/apartment-1.2.0/lib/apartment/adapters/abstract_adapter.rb:91:in `block in switch!'
/var/lib/gems/2.3.0/gems/activesupport-5.1.3/lib/active_support/callbacks.rb:97:in `run_callbacks'
/var/lib/gems/2.3.0/gems/apartment-1.2.0/lib/apartment/adapters/abstract_adapter.rb:88:in `switch!'
/var/lib/gems/2.3.0/gems/apartment-1.2.0/lib/apartment/adapters/abstract_adapter.rb:105:in `switch'
/home/user1/Desktop/SPERICORN/kidversity/lib/tasks/dynamic_age_setter.rake:4:in `block (2 levels) in <top (required)>'
/var/lib/gems/2.3.0/gems/rake-12.0.0/exe/rake:27:in `<top (required)>'
ActiveRecord::StatementInvalid: Could not find schema kochi
/var/lib/gems/2.3.0/gems/apartment-1.2.0/lib/apartment/adapters/postgresql_adapter.rb:66:in `connect_to_new'
/var/lib/gems/2.3.0/gems/apartment-1.2.0/lib/apartment/adapters/abstract_adapter.rb:91:in `block in switch!'
/var/lib/gems/2.3.0/gems/activesupport-5.1.3/lib/active_support/callbacks.rb:97:in `run_callbacks'
/var/lib/gems/2.3.0/gems/apartment-1.2.0/lib/apartment/adapters/abstract_adapter.rb:88:in `switch!'
/var/lib/gems/2.3.0/gems/apartment-1.2.0/lib/apartment/adapters/abstract_adapter.rb:105:in `switch'
/home/user1/Desktop/SPERICORN/kidversity/lib/tasks/dynamic_age_setter.rake:4:in `block (2 levels) in <top (required)>'
/var/lib/gems/2.3.0/gems/rake-12.0.0/exe/rake:27:in `<top (required)>'
Tasks: TOP => db:dynamic_age_setter
(See full trace by running task with --trace)
you are missing ActiveRecord::Base.establish_connection.connection try this
sample code below :
namespace :debtor_email_data_fix do
desc 'update data'
task email_normalize_to_downcase: :environment do
create_connection_with_db
Apartment::Tenant.switch!('app')
Email.find_each do |t|
t.update(address: t.address.downcase)
end
end
task all: [:email_normalize_to_downcase] do
end
private
def create_connection_with_db
ActiveRecord::Base.establish_connection.connection
end
end

Rails error Uninitialized constant importing csv

This is my first time importing a csv file to my rails app.
I have the code below in /lib/tasks/import.rake
require 'csv'
CSV.foreach("lib/articles.csv", headers: true, encoding: "ISO8859-1") do |row|
Article.new(title: row["Title"], body: row["Body"], user: User.find(1))
end
When I run rake import:articles
I get this error:
NameError: uninitialized constant Article
/Users/justinMgrant/code/hrsurvival/lib/tasks/import.rake:8:in `block in <top (required)>'
/Users/justinMgrant/code/hrsurvival/lib/tasks/import.rake:7:in `<top (required)>'
/Users/justinMgrant/.rvm/gems/ruby-2.2.1/gems/railties-4.2.2/lib/rails/engine.rb:658:in `block in run_tasks_blocks'
/Users/justinMgrant/.rvm/gems/ruby-2.2.1/gems/railties-4.2.2/lib/rails/engine.rb:658:in `each'
/Users/justinMgrant/.rvm/gems/ruby-2.2.1/gems/railties-4.2.2/lib/rails/engine.rb:658:in `run_tasks_blocks'
/Users/justinMgrant/.rvm/gems/ruby-2.2.1/gems/railties-4.2.2/lib/rails/application.rb:452:in `run_tasks_blocks'
/Users/justinMgrant/.rvm/gems/ruby-2.2.1/gems/railties-4.2.2/lib/rails/engine.rb:453:in `load_tasks'
/Users/justinMgrant/code/hrsurvival/Rakefile:6:in `<top (required)>'
(See full trace by running task with --trace)
Any idea what I’m doing wrong?
The problem is that you're not actually defining your task in your rakefile. This should work for you to be able to run rake import:articles.
namespace :import do
desc 'An optional description for what the task does'
task :articles => :environment do
# your code goes here
end
end
rake import:articles is saying to look for a task called articles within a namespace called import, which is why the namespace is necessary for what you're currently trying.
And as #max mentioned, utilizing task :articles => :environment is what tells the task to run in the context of your Rails environment, which would make your Articles model and any other model available to you in that task.

Rails populate db rake task OpenURI::HTTPError: 500 Internal Server Error

I am trying to make rake task to populate db from JSON API fixer.io,
but when i type my rake :
rake db:populate
this error occurs:
OpenURI::HTTPError: 500 Internal Server Error
/home/jakub/Documents/workspace/exch/lib/tasks/populate.rake:16:in `block (5 levels) in <top (required)>'
/home/jakub/Documents/workspace/exch/lib/tasks/populate.rake:13:in `block (4 levels) in <top (required)>'
/home/jakub/Documents/workspace/exch/lib/tasks/populate.rake:12:in `each'
/home/jakub/Documents/workspace/exch/lib/tasks/populate.rake:12:in `block (3 levels) in <top (required)>'
/home/jakub/Documents/workspace/exch/lib/tasks/populate.rake:11:in `each'
/home/jakub/Documents/workspace/exch/lib/tasks/populate.rake:11:in `block (2 levels) in <top (required)>'
Tasks: TOP => db:populate
(See full trace by running task with --trace)
This is my rake task (populate.rake) in lib/tasks:
require 'open-uri'
namespace :db do
desc "Erase and fill database"
task :populate => :environment do
require 'populator'
[ConversionRate].each(&:delete_all)
n = JSON.load(open('http://api.fixer.io/latest'))["rates"].keys.count
currencies = JSON.load(open('http://api.fixer.io/latest'))["rates"].keys
currencies.each do |curr1|
currencies.each do |curr2|
ConversionRate.populate 1 do |cr|
cr.currency1 = curr1
cr.currency2 = curr2
cr.conversion_rate = JSON.load(open('http://api.fixer.io/latest?base=' + curr1))["rates"][curr2]
end
end
end
end
end
Please help me, I have no idea what causes this problem.
the main problem is here, you are not taking keys of "rates"
currencies = JSON.load(open('http://api.fixer.io/latest')).keys
currencies = JSON.load(open('http://api.fixer.io/latest'))["rates"].keys
require 'open-uri'
namespace :db do
desc "Erase and fill database"
task :populate => :environment do
require 'populator'
[ConversionRate].each(&:delete_all)
latest_data = JSON.load(open('http://api.fixer.io/latest'))
currencies = latest_data["rates"].keys
n = currencies.count
currencies.each do |curr1|
currencies.each do |curr2|
ConversionRate.populate 1 do |cr|
#take care of any error, as we are going to call third party api here
begin
cr.currency1 = curr1
cr.currency2 = curr2
cr.conversion_rate = JSON.load(open('http://api.fixer.io/latest?base=' + curr1))["rates"][curr2]
rescue => e
puts "error #{e}"
end
end
end
#give a bit rest
sleep 2
end
end
end

Import old database into new schema in Rails

I want to import my old database to new schema in rails.
For that i have .rake file:
# /lib/tasks/project_name.rake:
namespace :project_name do
require Rails.root + "lib/tasks/importer"
desc "Import old database, usage: rake project_name:import['old_database_name']"
task :import, :oldDatabase, needs::environment do |t, args|
args.with_defaults(oldDatabase: "import")
oldDatabaseName = args.oldDatabse
newDatabaseName = YAML::load(IO.read(Rails.root.join("config/database.yml")))[Rails.env]["database"]
importer = Importer.new newDatabaseName, oldDatabaseName
importer.execute
end
end
but after adding that file I can't even use any rake command.
Here is some lines of trace:
no implicit conversion of pathname into string
/Users/user/Desktop/rails/dis/lib/tasks/project_name.rake:2:in `block in <top (required)>'
/Users/user/Desktop/rails/dis/lib/tasks/project_name.rake:1:in `<top (required)>'
I am doing it by looking at this tutorial:
http://www.frick-web.at/blog/import-old-database-in-new-schema-with-mysql-and-rails
try
require Rails.root.join("lib/tasks/importer").to_s

Rake task doesn't work in production

I have this rake task in a Rails 3.2.11 application in lib/rake/searches.rb:
namespace :searches do
desc "Start background searches"
task :start => :environment do
Rails.logger.info "Starting searches..."
Campaign.all.each do |c|
next unless c.recurring?
Rails.logger.info "Starting searches for campaign '#{c.name}'"
SearchWorker.enqueue(:campaign_id => c.id, :clear => true)
end
end
end
When I run it locally everything goes well. When I run it in production it errors out:
$ bundle exec rake searches:start
rake aborted!
uninitialized constant SearchWorker
/var/apps/web/lib/tasks/searches.rake:9:in `block (3 levels) in <top (required)>'
/var/apps/web/lib/tasks/searches.rake:5:in `block (2 levels) in <top (required)>'
Tasks: TOP => searches:start
(See full trace by running task with --trace)
When I jump into a console session, I can see that the class is correctly auto loaded:
$ bundle exec rails console
Loading production environment (Rails 3.2.11)
irb(main):001:0> SearchWorker
=> SearchWorker
This workers live in app/workers and they are added to the autoload_paths config setting in application.rb:
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
config.autoload_paths += %W(
#{config.root}/custom_scripts
#{config.root}/app/workers
#{config.root}/app/models/filters
)
So I have no clue why the error only occurs in production, and when running from a rake task.
Any ideas?
It seems you have created the rake file with .rb extension
lib/rake/searches.rb
can you try changing it to
lib/rake/searches.rake
That should work
This is due to the production environment in Rails 3.2 not being fully loaded, after the :environment task is complete.
If you explicitly require SearchWorker ie.
require 'app/workers/search_worker'
Within the beginning of the task block, it'll work.
(Why auto-loads isn't doing this for you, I don't know)

Resources