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.
Related
I am trying to upgrade a Rails 6.1.3.1 application from Ruby 2.6.6 to 3.0.0
All the rspec tests run fine and the in development everything seems to work just fine except one thing:
Even the simplest of tasks fails with this error:
"class variable ##debug_missing_translation of ActionView::Base is overtaken by Object"
For example, this simpletask.rake file
task simpletask: :environment do
puts 'Hello'
end
is not able to run as I get the following error:
lxxx#xxx:~/Workspace/edumino$ rails simpletask
rails aborted!
class variable ##debug_missing_translation of ActionView::Base is overtaken by Object
/home/xxx/railsapp/config/environment.rb:5:in `<top (required)>'
/home/xxx/railsapp/bin/rails:5:in `require'
/home/xxx/railsapp/bin/rails:5:in `<top (required)>'
/home/xxx/railsapp/bin/spring:10:in `require'
/home/xxx/railsapp/bin/spring:10:in `block in <top (required)>'
/home/xxx/railsapp/bin/spring:7:in `<top (required)>'
Tasks: TOP => simpletask => environment
(See full trace by running task with --trace)
...so, it turns out the problem was an already existing task. I don't remember exactly why this was necessary but the task had this:
# frozen_string_literal: true
require "#{Rails.root}/app/helpers/cron_helper"
require "#{Rails.root}/app/helpers/notifier_helper"
require "#{Rails.root}/app/helpers/application_helper"
include ApplicationHelper
include ActionView::Helpers::TranslationHelper
include CronHelper
namespace :cron do
task sms: :environment do |_t, _args|
...
end
end
I assume that the guilty code was including the ActionView::Helpers::TranslationHelper
Again, I can't remember why I had to do that at that time. But if you bump into this kind of 'overtaken by' error when upgrading to Ruby 3.0, check your other tasks and see what kinda weird includes you might have had. In my case, since I didn't need the old task, I just removed it.
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
I have a rake task which is called by a third party service. In my application I need to set Customer before starting the application. I could not access the model variable from the rake task. But this happens only in Production not in Development. When I run
RAILS_ENV = 'production' rake auth:tester
I get the followng error.
rake aborted!
Unable to autoload constant CUSTOMER, expected /home/suganya/academics/tsg-mcds-server/app/models/customer.rb to define it
/home/suganya/.rvm/gems/ruby-2.0.0-p353/gems/activesupport-4.2.7.1/lib/active_support/dependencies.rb:495:in `load_missing_constant'
/home/suganya/.rvm/gems/ruby-2.0.0-p353/gems/activesupport-4.2.7.1/lib/active_support/dependencies.rb:184:in `const_missing'
/home/suganya/academics/tsg-mcds-server/config/initializers/customer_config.rb:11:in `xml'
/home/suganya/academics/tsg-mcds-server/config/initializers/customer_config.rb:38:in `set_customer_settings'
/home/suganya/academics/tsg-mcds-server/config/initializers/customer_config.rb:710:in `<top (required)>'
/home/suganya/.rvm/gems/ruby-2.0.0-p353/gems/activesupport-4.2.7.1/lib/active_support/dependencies.rb:268:in `load'
/home/suganya/.rvm/gems/ruby-2.0.0-p353/gems/activesupport-4.2.7.1/lib/active_support/dependencies.rb:268:in `block in load'
/home/suganya/.rvm/gems/ruby-2.0.0-p353/gems/activesupport-4.2.7.1/lib/active_support/dependencies.rb:240:in `load_dependency'
/home/suganya/.rvm/gems/ruby-2.0.0-p353/gems/activesupport-4.2.7.1/lib/active_support/dependencies.rb:268:in `load'
/home/suganya/.rvm/gems/ruby-2.0.0-p353/gems/railties-4.2.7.1/lib/rails/engine.rb:652:in `block in load_config_initializer'
I have referred all the related questions. When I enable in poduction.rb
config.threadsafe!
config.dependency_loading = true if $rails_rake_task
I get the following error.
undefined method `threadsafe!' for #<Rails::Application::Configuration:0x00000004aebdf8>
Also I tried
Rails.application.eager_load!
this is my rake task:
namespace :authentication do
desc "Automatically runs authentication tester"
task :tester => :environment do
Rake.application.rake_require "#{Rails.root}/config/initialize_customer_in_development.rb"
begin
AuthenticationTester.perform
rescue
SystemEvent.error(50049, "Authentication Tester Finished Unsuccessfully.")
end
end
end
Nothing helped. please help to solve this problem.
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
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