Rails console: NameError: uninitialized constant - ruby-on-rails

I just added a new model to my app named Collector.
I'm trying to make some data changes using the console on my server:
GsCollector.all.each do |gsc|
coll = Collector.new
coll.project_id = gsc.project_id
coll.kind = 'GsCollector'
coll.optional = gsc.optional
coll.included = gsc.included
coll.save
gsc.collector_id = coll.id
gsc.save
gsc.custom_descriptions.each do |cd|
cd.collector_id = coll.id
cd.save
end
gsc.order_notes.each do |note|
note.collector_id = coll.id
note.save
end
end
But this fails with:
GsCollector Load (0.3ms) SELECT `gs_collectors`.* FROM `gs_collectors`
NameError: uninitialized constant Collector
from (irb):2:in `block in irb_binding'
from (irb):1:in `each'
from (irb):1
What's wrong here? These commands in the console on my dev machine worked fine. I did migrate the database on the server.

Run the The command
reload!
Or restart your terminals to get good result

Related

I was trying to run a rake task, and got the error NameError: uninitialized constant User [duplicate]

This question already has answers here:
Do rails rake tasks provide access to ActiveRecord models?
(6 answers)
Closed 14 days ago.
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!
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

Using Ruby Gem That Uses an API - Setting Up Client

I am using Ruby on Rails. I am trying to implement https://www.kraken.com/help/api
Incase it isn't obvious, my knowledge of implementing API's and gems is very basic.
I go to the "example-api-code" paragraph and I get to https://github.com/leishman/kraken_ruby
I include the gem and do the bundle.
Now we get to "Usage" "Create A Client"
I assume I put the following in config/kraken.rb
API_KEY = '3bH+M/nLp......'
API_SECRET = 'wQG+7Lr9b.....'
kraken = Kraken::Client.new(API_KEY, API_SECRET)
time = kraken.server_time
time.unixtime #=> 1393056191
I wanted to test something simple, such as displaying the time.
I put the following code in my views/welcome/index.html.erb file, but then I get an error.
<p><%= kraken.server_time %></p>
-> ActionView::Template::Error (undefined local variable or method `kraken' for #<#<Class:0x007f95c6246ba8>:0x007f95c6245eb0>):
Trying this code in my html.erb file and it gives me another error
<p><%= #kraken.server_time %></p>
-> ActionView::Template::Error (undefined method `server_time' for nil:NilClass):
-------------------------------------------------------------------------------
EDIT: Solutions Attempts, TLDR NameError (uninitialized constant...
# Gladis
Using your solution I get this error
->! Unable to load application: SyntaxError: /app/app/controllers/welcome_controller.rb:5: dynamic constant assignment
-> API_KEY = '...'
So I tried
def index
#kraken = Kraken::Client.new('3bH+M/nLp...', 'wQG+7Lr9b...')
time = #kraken.server_time
time.unixtime #=> 1393056191
end
and got this new error
NameError (uninitialized constant WelcomeController::Kraken):
app/controllers/welcome_controller.rb:5:in `index'
# Pavel Tkackenko
Your first solution (wrapping in singleton-like class) gives me this error.
ActionView::Template::Error (uninitialized constant ActionView::CompiledTemplates::KrakenClient):
app/views/welcome/index.html.erb:1:in `_app_views_welcome_index_html_erb__3584347874708863751_70226442404480'
1: <p><%= KrakenClient.get.server_time %></p>
Your second solutions (monkey-patch) gives me the this error.
ActionView::Template::Error (uninitialized constant ActionView::CompiledTemplates::Kraken):
1: <p><%= Kraken.client.server_time %></p>
app/views/welcome/index.html.erb:1:in `_app_views_welcome_index_html_erb___3719740865851336982_69820265644620'
Moving /config/kraken.rb to /config/initializers/kraken.rb using Pavel's method
Wrapping it in singleton-like class gives me this error (infact, it doesn't even let me host the server)
->When I host it on my local computer with bin/rails server
/config/initializers/kraken.rb:6:in `<class:KrakenClient>': uninitialized constant KrakenClient::Kraken (NameError)
/config/initializers/kraken.rb:1:in `<top (required)>'
->When I host it on heroku
Running: rake assets:precompile
rake aborted!
NameError: uninitialized constant KrakenClient::Kraken
/config/initializers/kraken.rb:5:in `<class:KrakenClient>'
/config/initializers/kraken.rb:1:in `<top (required)>'
...
/config/environment.rb:5:in `<top (required)>'
With monkey-patch I get this error
ActionView::Template::Error (uninitialized constant Kraken::Client):
1: <p><%= Kraken.client.server_time %></p>
config/initializers/kraken.rb:8:in `client'
app/views/welcome/index.html.erb:1:in `_app_views_welcome_index_html_erb___577296263292451462_70097201303100'
If you got it to work on your computer, I would be happy to use your code as a skeleton (I am assuming this will be easier than figuring out what's wrong on my side).
Put this code in WelcomeController.rb
def index
API_KEY = '3bH+M/nLp......'
API_SECRET = 'wQG+7Lr9b.....'
#kraken = Kraken::Client.new(API_KEY, API_SECRET)
time = #kraken.server_time
time.unixtime #=> 1393056191
end
In view under this controller put:
<p><%= #kraken.server_time %></p>
kraken = Kraken::Client.new(API_KEY, API_SECRET)
kraken here is local variable. If you put it into config/kraken.rb, it will not be accessible outside.
There are different solutions. One is to wrap it in singleton-like class:
# config/initializers/kraken.rb
class KrakenClient
API_KEY = '3bH+M/nLp......'
API_SECRET = 'wQG+7Lr9b.....'
##config = Kraken::Client.new(API_KEY, API_SECRET)
def self.get
##config
end
end
# index.html.erb
<p><%= KrakenClient.get.server_time %></p>
Another one approach is to monkey-patch Kraken itself:
# config/initializers/kraken.rb
class Kraken
API_KEY = '3bH+M/nLp......'
API_SECRET = 'wQG+7Lr9b.....'
class << self
def client
#client ||= Kraken::Client.new(API_KEY, API_SECRET)
end
end
end
# index.html.erb
<p><%= Kraken.client.server_time %></p>

Why is irb returning NameError: uninitialized constant for all objects in the database?

I am half way through building a Q&A app and I have successfully seeded my database and can see that objects have been created both in my browser and in the server logs and previously in irb. Now when I went to try to inspect an object in irb, for every object I give it, irb returns "NameError: uninitialized constant". For example:
2.0.0-p481 :001 > user = User.find(1)
NameError: uninitialized constant User
from (irb):1
from /home/vagrant/.rvm/rubies/ruby-2.0.0-p481/bin/irb:12:in `<main>'
2.0.0-p481 :002 > question = Question.find(1)
NameError: uninitialized constant Question
from (irb):2
from /home/vagrant/.rvm/rubies/ruby-2.0.0-p481/bin/irb:12:in `<main>'
2.0.0-p481 :003 > user = User.find
NameError: uninitialized constant User
from (irb):3
from /home/vagrant/.rvm/rubies/ruby-2.0.0-p481/bin/irb:12:in `<main>'
2.0.0-p481 :004 > user = User.new
NameError: uninitialized constant User
from (irb):4
from /home/vagrant/.rvm/rubies/ruby-2.0.0-p481/bin/irb:12:in `<main>'
I'm new to programming, so if anyone could explain why this might be happening it would be much appreciated!
It looks like you're running irb when you want rails console (or rails c for short).
Because you need to use rails console, not irb.
rails console
(I assume you are building a Rails application)

New to Ruby trying to learn how to debug

I am migrating data from a database and getting an error I cannot understand. I am new to Ruby and am looking for both what is wrong with my code and also the most effective commands for debugging. I cannot even really read my error.
Here is my error:
/Users/skline/.rvm/gems/ruby-1.9.2-p136#rails3tutorial/gems/activemodel-3.0.6/lib/active_model/attribute_methods.rb:367:in `method_missing': undefined method `answer=' for #<Question:0x00000102d59758> (NoMethodError)
from /Users/skline/.rvm/gems/ruby-1.9.2-p136#rails3tutorial/gems/activerecord-3.0.6/lib/active_record/attribute_methods.rb:46:in `method_missing'
from ./script/migrate.rb:139:in `block (2 levels) in <main>'
from /Users/skline/.rvm/gems/ruby-1.9.2-p136#rails3tutorial/gems/activerecord-3.0.6/lib/active_record/relation.rb:13:in `each'
from /Users/skline/.rvm/gems/ruby-1.9.2-p136#rails3tutorial/gems/activerecord-3.0.6/lib/active_record/relation.rb:13:in `each'
from ./script/migrate.rb:137:in `block in <main>'
from ./script/migrate.rb:111:in `each'
from ./script/migrate.rb:111:in `<main>'
Any tips for reading this error and for how to debug.
Note here is my code:
NetworkCommunications.all.each do |nc|
if nc.NETWORK_COMM_TYPE_ID==1 && nc.SENDER_CONSUMER_ID != 0
q = Question.new
q.created_at = nc.LAST_MOD_TIME
category = CommunicationInterestMapping.where(:COMMUNICATION_ID => nc.COMMUNICATIONS_ID).first
if category
cie = ConsumerInterestExpertLookup.find(category.CONSUMER_INTEREST_EXPERT_ID)
if cie
q.category = Category.find_by_name cie.CONSUMER_INTEREST_EXPERT_NAME
else
puts "No category"
end
end
message = NetworkCommunicationsMessage.where(:COMMUNICATIONS_ID => nc.COMMUNICATIONS_ID).first
q.title = message.SUBJECT
q.description = message.MESSAGE
q.permalink = message.QUESTION_SLUG
email = find_email_from_consumer_id(nc.SENDER_CONSUMER_ID)
q.user = User.find_by_email email
children = NetworkCommunications.where(:PARENT_COMMUNICATIONS_ID => nc.COMMUNICATIONS_ID)
puts children
if children
children.each do |ncc|
if ncc.NETWORK_COMM_TYPE_ID == 2
q.answer = Answer.new
q.answer.created_at = ncc.LAST_MOD_TIME
message_a = NetworkCommunicationsMessage.where(:COMMUNICATIONS_ID => ncc.COMMUNICATIONS_ID).first
q.answer.text = message_a.MESSAGE
email_a = find_email_from_consumer_id(ncc.SENDER_CONSUMER_ID)
q.answer.user = User.find_by_email email_a
end
end
end
begin
q.save!
rescue Exception => e
puts "Exception: #{e} title: #{message.SUBJECT}"
end
end
end
To read the stack dump, look at the first line then read downwards:
/Users/skline/.rvm/gems/ruby-1.9.2-p136#rails3tutorial/gems/activemodel-3.0.6/lib/active_model/attribute_methods.rb:367:in `method_missing': undefined method `answer=' for #<Question:0x00000102d59758> (NoMethodError)
from /Users/skline/.rvm/gems/ruby-1.9.2-p136#rails3tutorial/gems/activerecord-3.0.6/lib/active_record/attribute_methods.rb:46:in `method_missing'
from ./script/migrate.rb:139:in `block (2 levels) in <main>'
The first line tells you where the problem was triggered and why: In ActiveModel's attribute_methods method because no setter for answer was found in the object. This was triggered from a call in line 139 of your migrate.rb script. The trick with a stack trace is to read through it, looking for the scripts you've written. Odds are really good the problem is in our code so it's always good to start from the assumption the bug is ours.
if ncc.NETWORK_COMM_TYPE_ID == 2
q.answer = Answer.new
is where the problem is. Your Question class doesn't have a setter for answer. Either you're missing or misspelled an attribute_accessor call or misspelled a def answer= method.
To debug I recommend using Ruby Debugger 1.9. gem install ruby-debug19. It's 1.9.2 studly and easy to use. You can set a breakpoint in your code, then run it from the command-line, which will run until the breakpoint is reached and will stop in the debugger. From there you can list the current lines using l, display the contents of variables using p or do a require 'pp' if you have pretty-printer installed. You can single-step into methods using s or step over them using n, for "next". There's also c to continue, c 100 to continue to a particular line number; 100 in that example. You can use b 100 to set a break-point at line 100, and then c to run, stopping at 100 every time. irb will drop you into IRB with the variables to that point already initialized so you can poke at them. There are lots of other commands, but those are the ones I use most often.
It probably means you have defined the answer attribute for your question class:
class Question < ActiveRecord::Base
attr_accessor :answer
[...]
end
You should also learn how to use rdebug so that you can step through the code and figure this out without help.
I think your model Question doesn't have answer attribute.
In this cast you can study how to debug rails app

Rails 3 - Paperclip: uninitialized constant ActionDispatch::Request::UploadedFile

I have a confusing error:
I run Rails 3.0.0 on Ruby 1.9.2 with Paperclip 2.3.5.
When I upload a file I get a 500 error.
NameError (uninitialized constant ActionDispatch::Request::UploadedFile):
config/initializers/fix_params.rb:13:in `normalize_parameters'
config/initializers/fix_params.rb:19:in `block in normalize_parameters'
config/initializers/fix_params.rb:19:in `each'
config/initializers/fix_params.rb:19:in `normalize_parameters'
config/initializers/fix_params.rb:19:in `block in normalize_parameters'
config/initializers/fix_params.rb:19:in `each'
config/initializers/fix_params.rb:19:in `normalize_parameters'
Rendered /Users/vjmayr/.rvm/gems/ruby-1.9.2-p0/gems/actionpack-3.0.0/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (10.2ms)
I have seen similar things happen with Rails 3.0.2 and .3 but I have no idea why it happens here. Con anyone help me with finding the problem?
Thanks! Valentin
ADDED config/initializers/fix_params.rb:
module ActionController
class Request
private
# Convert nested Hashs to HashWithIndifferentAccess and replace
# file upload hashs with UploadedFile objects
def normalize_parameters(value)
case value
when Hash
if value.has_key?(:tempfile)
upload = value[:tempfile]
upload.extend(UploadedFile)
upload.original_path = value[:filename]
upload.content_type = value[:type]
upload
else
h = {}
value.each { |k, v| h[k] = normalize_parameters(v) }
h.with_indifferent_access
end
when Array
value.map { |e| normalize_parameters(e) }
else
value.force_encoding(Encoding::UTF_8) if value.respond_to?(:force_encoding)
value
end
end
end
end
tadman (Thanks!) pointed me towards the right solution:
All I had to do was change the value from tempfile to to_tempfile. This prabably won't happen to too many people, but I thought I'd mention as there has been a similar discussion around that due to a recent change in stable rails 3.0.3 by tenderlove, which is philisophically absolutely correct - but threw off some people...
So here is the changed fragment of fix_params.rb
...
if value.has_key?(:to_tempfile)
upload = value[:to_tempfile]
...
Cheers,
Val

Resources