factory_girl is not recognizing a model name that I've defined, and which I need to reference because I need a subclass. This worked in rails 2 but I'm migrating to rails 3.
Factory definition:
Factory.define :interest, :class => Term::Interest do |f|
f.name {"#{Factory.next(:lipsum_word)}ing"}
end
Definition of Term and Term::Interest
class Term < ActiveRecord::Base
belongs_to :category
class Interest < Term
end
class Award < Term
end
end
Error and stack trace:
$ rake db:data:load --trace
(in /Users/glurban/code/recruitd)
rake aborted!
uninitialized constant Term
/Users/glurban/.rvm/gems/ruby-1.9.2-rc2/gems/rspec-core-2.4.0/lib/rspec/core/backward_compatibility.rb:20:in `const_missing'
/Users/glurban/code/recruitd/test/factories/factories.rb:316:in `<top (required)>'
/Users/glurban/code/recruitd/lib/tasks/use_factories.rake:2:in `<top (required)>'
/Users/glurban/.rvm/gems/ruby-1.9.2-rc2/gems/railties-3.0.0/lib/rails/engine.rb:131:in `block in load_tasks'
/Users/glurban/.rvm/gems/ruby-1.9.2-rc2/gems/railties-3.0.0/lib/rails/engine.rb:131:in `each'
/Users/glurban/.rvm/gems/ruby-1.9.2-rc2/gems/railties-3.0.0/lib/rails/engine.rb:131:in `load_tasks'
/Users/glurban/.rvm/gems/ruby-1.9.2-rc2/gems/railties-3.0.0/lib/rails/application.rb:141:in `load_tasks'
/Users/glurban/.rvm/gems/ruby-1.9.2-rc2/gems/railties-3.0.0/lib/rails/application.rb:77:in `method_missing'
/Users/glurban/code/recruitd/Rakefile:7:in `<top (required)>'
/Users/glurban/.rvm/gems/ruby-1.9.2-rc2/gems/rake-0.8.7/lib/rake.rb:2383:in `load'
/Users/glurban/.rvm/gems/ruby-1.9.2-rc2/gems/rake-0.8.7/lib/rake.rb:2383:in `raw_load_rakefile'
/Users/glurban/.rvm/gems/ruby-1.9.2-rc2/gems/rake-0.8.7/lib/rake.rb:2017:in `block in load_rakefile'
/Users/glurban/.rvm/gems/ruby-1.9.2-rc2/gems/rake-0.8.7/lib/rake.rb:2068:in `standard_exception_handling'
/Users/glurban/.rvm/gems/ruby-1.9.2-rc2/gems/rake-0.8.7/lib/rake.rb:2016:in `load_rakefile'
/Users/glurban/.rvm/gems/ruby-1.9.2-rc2/gems/rake-0.8.7/lib/rake.rb:2000:in `block in run'
/Users/glurban/.rvm/gems/ruby-1.9.2-rc2/gems/rake-0.8.7/lib/rake.rb:2068:in `standard_exception_handling'
/Users/glurban/.rvm/gems/ruby-1.9.2-rc2/gems/rake-0.8.7/lib/rake.rb:1998:in `run'
/Users/glurban/.rvm/gems/ruby-1.9.2-rc2/gems/rake-0.8.7/bin/rake:31:in `<top (required)>'
/Users/glurban/.rvm/gems/ruby-1.9.2-rc2/bin/rake:19:in `load'
/Users/glurban/.rvm/gems/ruby-1.9.2-rc2/bin/rake:19:in `<main>'
I tried adding require_dependency 'term' to the top of factories.rb but then I get
Glens-MacBook-Pro:test glurban$ rake db:data:load
(in /Users/glurban/code/recruitd)
rake aborted!
No such file to load -- term
What to do?
Edit: in response to the comment, yes, it happens only on rake, not in the console:
$ rails c
Loading development environment (Rails 3.0.0)
ruby-1.9.2-rc2 > Factory(:term)
=> #<Term id: 3, type: nil, name: "Proud to be a Recruitd user", location: nil, category_id: nil, description: nil, url: nil, created_at: "2011-01-06 21:30:14", updated_at: "2011-01-06 21:30:14">
ruby-1.9.2-rc2 > Factory(:interest)
=> #<Term::Interest id: 4, type: "Term::Interest", name: "siting", location: nil, category_id: nil, description: nil, url: nil, created_at: "2011-01-06 21:30:18", updated_at: "2011-01-06 21:30:18">
Custom rake task definition:
require 'factory_girl'
require File.expand_path("test/factories/factories.rb")
namespace :db do
namespace :data do
desc "Load sample data"
task :load => :environment do |t|
create_students
...
create_student_files_and_feeds
puts "Completed loading sample data."
end
end
end
def create_interests
data_fetch("interests").each do |input|
Factory(:interest, :name => input.strip)
end
puts "Created interests"
end
After looking over the factory_girl documentation again, I realized that you can specify a class using either a string or a class constant. So I tried using a string and it worked:
Factory.define :interest, :class => "Term::Interest" do |f|
f.name {"#{Factory.next(:lipsum_word)}ing"}
end
Also, a comment about the nested classes. I initially did that to keep the classes a little more organized, but given the complexity it's created (especially for routing), I'm just going to move each subclass to its own model file. (If I were to un-nest them without putting them in separate files, rails seems to fail to find the subclasses sometimes--namely if the parent class hadn't been referenced (forcing the load of that file) before.
Related
I do not know why this is breaking. I'm trying to run a migration on some code I've inherited and I've hit a snag. Here is the error message followed by the migration file code.
== AddStorecreditGizmoType: migrating ========================================
rake aborted!
NoMethodError: undefined method `find_by_name' for GizmoCategory(id: integer, description: string):Class
/var/lib/gems/1.9.1/gems/activerecord-2.3.14/lib/active_record/base.rb:1876:in `method_missing'
/home/thefonso/site-dev/vendor/plugins/will_paginate/lib/will_paginate/finder.rb:175:in `method_missing_with_paginate'
db/migrate//20090628000954_add_storecredit_gizmo_type.rb:4:in `up'
/var/lib/gems/1.9.1/gems/activerecord-2.3.14/lib/active_record/migration.rb:282:in `block in migrate'
/var/lib/gems/1.9.1/gems/activerecord-2.3.14/lib/active_record/migration.rb:282:in `migrate'
/var/lib/gems/1.9.1/gems/activerecord-2.3.14/lib/active_record/migration.rb:365:in `migrate'
/var/lib/gems/1.9.1/gems/activerecord-2.3.14/lib/active_record/migration.rb:457:in `run'
/var/lib/gems/1.9.1/gems/activerecord-2.3.14/lib/active_record/migration.rb:409:in `run'
/var/lib/gems/1.9.1/gems/rails-2.3.14/lib/tasks/databases.rake:135:in `block (3 levels) in <top (required)>'
/var/lib/gems/1.9.1/gems/rake-11.3.0/exe/rake:27:in `<top (required)>'
Tasks: TOP => db:migrate:up
(See full trace by running task with --trace)
Here is the migration file code
class AddStorecreditGizmoType < ActiveRecord::Migration
def self.up
# TODO: GizmoCategory.find_by_name("misc") is breaking...why? Attempted to replace with "where" but same error.
new = GizmoType.new(:name => "store_credit", :description => "Store Credit", :gizmo_category => GizmoCategory.find_by_name("misc"), :required_fee_cents => 0, :suggested_fee_cents => 0)
new.save!
DB.execute("UPDATE gizmo_contexts_gizmo_types SET gizmo_type_id = #{new.id} WHERE gizmo_type_id IN (SELECT id FROM gizmo_types WHERE name = 'gift_cert');")
end
def self.down
DB.execute("UPDATE gizmo_contexts_gizmo_types SET gizmo_type_id = (SELECT id FROM gizmo_types WHERE name = 'gift_cert') WHERE gizmo_type_id IN (SELECT id FROM gizmo_types WHERE name = 'store_credit');")
GizmoType.find_by_name("store_credit").destroy
end
end
I've tried using "where" and "Find_by" but I keep getting this same "undefined method blahblah for GizmoCategory
Can you point me in the right direction? What am I missing? forgetting? What's happening here?
Oh and versions are as follows
rails - 2.3.14
ruby - 1.9.3p194
Thanks
The find_by_* methods didn't exist in activerecord 2.3.14. Use Model.find instead.
category = GizmoCategory.find(:first, conditions: "name = 'store_credit'")
category.destroy if category
Let's say I have a ruby or json file consisting of hashes and range anywhere from 14-20MB (300K lines unminified). I've created a rake task which loops through each hash and creates an AR object based on the values in each hash.
Unfortunately due to the file's size I get stack level too deep errors each time I run the task. The only way I've actually gotten the script to run is by splitting the file into smaller ones. Although this works, it gets extremely tedious to split the file and repeat the task over and over. Are there any good alternatives for loading/running large files?
Rake Task
namespace :db do
task populate: :environment do
$restaurants.each_with_index do |r, index|
uri = URI(r[:website])
restaurant = Restaurant.find_or_create_by(name: r[:name], website: "#{uri.scheme}://#{uri.host}")
restaurant.cuisines = r[:cuisines].map { |c| Cuisine.find_or_create_by(name: c) }
location = Location.create(
restaurant: restaurant,
city_id: 1,
address: r[:address],
latitude: r[:latitude],
longitude: r[:longitude],
phone_number: r[:phone_number]
)
r[:hours].each do |h|
Hour.create(
location: location,
day: Date::DAYNAMES.index(h[:day]),
opens: h[:opens],
closes: h[:closes]
)
end
menu_group = MenuGroup.create(
restaurant: restaurant,
locations: [location],
address: r[:address]
)
r[:menus].each do |m|
menu = Menu.create(
menu_group: menu_group,
position: m[:position],
name: m[:name]
)
m[:sections].each do |s|
section = Section.create(
menu: menu,
position: s[:position],
name: s[:name]
)
s[:dishes].each do |d|
tag = Tag.find_or_create_by(
name: d[:name].downcase.strip
)
Dish.find_or_create_by(
restaurant: restaurant,
sections: [section],
tags: [tag],
name: d[:name],
description: d[:description]
)
end
end
end
puts "#{index + 1} of #{$restaurants.size} completed"
end
end
end
Error
rake aborted!
SystemStackError: stack level too deep
/usr/local/lib/ruby/gems/2.5.0/gems/bootsnap-1.3.1/lib/bootsnap/compile_cache/iseq.rb:12:in`to_binary'
/usr/local/lib/ruby/gems/2.5.0/gems/bootsnap-1.3.1/lib/bootsnap/compile_cache/iseq.rb:12:in`input_to_storage'
/usr/local/lib/ruby/gems/2.5.0/gems/bootsnap-1.3.1/lib/bootsnap/compile_cache/iseq.rb:37:in`fetch'
/usr/local/lib/ruby/gems/2.5.0/gems/bootsnap-1.3.1/lib/bootsnap/compile_cache/iseq.rb:37:in`load_iseq'
/usr/local/lib/ruby/gems/2.5.0/gems/bootsnap-1.3.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:21:in `require'
/usr/local/lib/ruby/gems/2.5.0/gems/bootsnap-1.3.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:21:in `block in require_with_bootsnap_lfi'
/usr/local/lib/ruby/gems/2.5.0/gems/bootsnap-1.3.1/lib/bootsnap/load_path_cache/loaded_features_index.rb:65:in `register'
/usr/local/lib/ruby/gems/2.5.0/gems/bootsnap-1.3.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:20:in `require_with_bootsnap_lfi'
/usr/local/lib/ruby/gems/2.5.0/gems/bootsnap-1.3.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:29:in `require'
/usr/local/lib/ruby/gems/2.5.0/gems/activesupport-5.2.0/lib/active_support/dependencies.rb:283:in `block in require'
/usr/local/lib/ruby/gems/2.5.0/gems/activesupport-5.2.0/lib/active_support/dependencies.rb:249:in `load_dependency'
/usr/local/lib/ruby/gems/2.5.0/gems/activesupport-5.2.0/lib/active_support/dependencies.rb:283:in `require'
/Users/user/app/lib/tasks/populate.rake:1:in `<main>'
/usr/local/lib/ruby/gems/2.5.0/gems/bootsnap-1.3.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:50:in `load'
/usr/local/lib/ruby/gems/2.5.0/gems/bootsnap-1.3.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:50:in `load'
/usr/local/lib/ruby/gems/2.5.0/gems/activesupport-5.2.0/lib/active_support/dependencies.rb:277:in `block in load'
/usr/local/lib/ruby/gems/2.5.0/gems/activesupport-5.2.0/lib/active_support/dependencies.rb:249:in `load_dependency'
/usr/local/lib/ruby/gems/2.5.0/gems/activesupport-5.2.0/lib/active_support/dependencies.rb:277:in `load'
/usr/local/lib/ruby/gems/2.5.0/gems/railties-5.2.0/lib/rails/engine.rb:650:in `block in run_tasks_blocks'
/usr/local/lib/ruby/gems/2.5.0/gems/railties-5.2.0/lib/rails/engine.rb:650:in `each'
/usr/local/lib/ruby/gems/2.5.0/gems/railties-5.2.0/lib/rails/engine.rb:650:in `run_tasks_blocks'
/usr/local/lib/ruby/gems/2.5.0/gems/railties-5.2.0/lib/rails/application.rb:515:in `run_tasks_blocks'
/usr/local/lib/ruby/gems/2.5.0/gems/railties-5.2.0/lib/rails/engine.rb:459:in `load_tasks'
/Users/user/app/Rakefile:6:in `<top (required)>'
/usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/exe/rake:27:in `<top (required)>'
(See full trace by running task with --trace)
I would use something like Sidekiq to break the jobs in to workers that can run concurrently.
For example:
$restaurants.each_with_index do |r, index|
RestaurantParser.perform_async(r, index)
end
In RestaurantParser perform the steps you would normally take.
As long as restaurants don't rely on other restaurants already existing in the DB you can run workers concurrently to speed up the process.
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
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.
first is the status:
class Status
include Mongoid::Document
field :name, type: String
has_one :Apis
validates_presence_of :name
end
as well have APIS:
class Apis
include Mongoid::Document
field :name, type: String
field :description, type: String, default: ''
field :create_at, type: DateTime, default: ->{ DateTime.now }
belongs_to :Status
validates_presence_of :name
end
the SEED file:
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
if Status.count == 0
Status.create({name: "active"})
Status.create({name: "inactive"})
Status.create({name: "pending"})
Status.create({name: "rejected"})
Status.create({name: "sending"})
Status.create({name: "contentItemPending"})
Status.create({name: "contentItemListed"})
Status.create({name: "staticItemListed"})
Status.create({name: "requestItemPending"})
end
if Apis.count == 0
active_status = Status.find_by({name:"active"})
youtub = Apis.new({name:"youtube", description:"Youtube API Used youtube_it gem"})
youtub.build_Status(active_status.id)
youtub.save!
itunes = Apis.new({name:"itunes", description:"ITUNES API Used itunes gem"})
itunes.build_Status(active_status.id)
itunes.save!
factual = Apis.new({name:"factual", description:"FACTUAL API Used FACTUAL gem"})
factual.build_Status(active_status.id)
factual.save!
end
now i get this error:
fastwings:Feelike-Agent/ (master✗) $ rake db:seed [14:21:41]
rake aborted!
uninitialized constant Statu
/usr/local/rvm/gems/ruby-1.9.3-p327#global/gems/activesupport-3.2.9/lib/active_support/inflector/methods.rb:230:in `block in constantize'
/usr/local/rvm/gems/ruby-1.9.3-p327#global/gems/activesupport-3.2.9/lib/active_support/inflector/methods.rb:229:in `each'
/usr/local/rvm/gems/ruby-1.9.3-p327#global/gems/activesupport-3.2.9/lib/active_support/inflector/methods.rb:229:in `constantize'
/usr/local/rvm/gems/ruby-1.9.3-p327#global/gems/activesupport-3.2.9/lib/active_support/core_ext/string/inflections.rb:54:in `constantize'
/usr/local/rvm/gems/ruby-1.9.3-p327/gems/mongoid-3.0.19/lib/mongoid/relations/metadata.rb:602:in `klass'
/usr/local/rvm/gems/ruby-1.9.3-p327/gems/mongoid-3.0.19/lib/mongoid/relations/builders.rb:68:in `block in builder'
/home/fastwings/Projects/Ruby/Feelike-Agent/db/seeds.rb:23:in `<top (required)>'
/usr/local/rvm/gems/ruby-1.9.3-p327/gems/mongoid-3.0.19/lib/mongoid/railties/database.rake:13:in `block (2 levels) in <top (required)>'
/usr/local/rvm/gems/ruby-1.9.3-p327/bin/ruby_noexec_wrapper:14:in `eval'
/usr/local/rvm/gems/ruby-1.9.3-p327/bin/ruby_noexec_wrapper:14:in `<main>'
Tasks: TOP => db:seed
(See full trace by running task with --trace)
now i got no clue what i doing here wrong what is here not work???
as well its make at line 23 means
youtub.build_Status(active_status.id) to uninitialized constant Statu why???
ok Guys its work my error was this:
belongs_to :Status , class_name: 'something'
and
has_one :Apis ,class_name:'something'
and the seeder need added like this:
Mongoid.purge!
if SystemStatus.count == 0
SystemStatus.create!({name: "active"})
SystemStatus.create!({name: "inactive"})
SystemStatus.create!({name: "pending"})
SystemStatus.create!({name: "rejected"})
SystemStatus.create!({name: "sending"})
SystemStatus.create!({name: "contentItemPending"})
SystemStatus.create!({name: "contentItemListed"})
SystemStatus.create!({name: "staticItemListed"})
SystemStatus.create!({name: "requestItemPending"})
end
if Providers.count == 0
active_status = SystemStatus.find_by({name:"active"})
Providers.create!({name:"youtube", description:"Youtube API Used youtube_it gem",status: active_status})
Providers.create!({name:"itunes", description:"Youtube API Used youtube_it gem",status: active_status})
Providers.create!({name:"youtube", description:"Youtube API Used youtube_it gem",status: active_status})
Providers.create!({name:"unknown", description:"Rest service conntection",status: active_status})
end
what that went wrong here was that it didnt know what class to go to as well how i enter the data
Besides the s missing, which that's what it looks like, I'm not sure if the Status.count will even work, I think you need to use Status.all.count, and other thing is you should use Status.create! with a bang (!). It will raise an exception if if there's an error. IF you use it without the bang, it'll return false but you won't know there's a problem.
You may have to set custom inflectors for your Status model. Fire up a console and try running "status".singularize to see what you get.