NameError in UsersController#show - ruby-on-rails

I am currently working on the Ruby on Rails tutorial by Michael Hartl. I am trying to add a page for each user in my database by creating an HTML with embedded ruby page in the views directory. The code for show.html.erb is below:
<%= #user.name %>, <%= #user.email %>
When I add the user to the user_controller.rb file, it looks like this:
class UsersController < ApplicationController
def show
#user = User.find(params[:id])
end
def new
end
end
When I run the rails server and click on open up the users/1 URL, I get a NameError complaining about an uninitialized constant. The error and trace is below:
NameError in UsersController#show
uninitialized constant UsersController::User
Rails.root: /usr/sample_app
Application Trace | Framework Trace | Full Trace
app/controllers/users_controller.rb:3:in `show'
actionpack (3.2.12) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
actionpack (3.2.12) lib/abstract_controller/base.rb:167:in `process_action'
actionpack (3.2.12) lib/action_controller/metal/rendering.rb:10:in `process_action'
actionpack (3.2.12) lib/abstract_controller/callbacks.rb:18:in `block in process_action'
activesupport (3.2.12) lib/active_support/callbacks.rb:414:in
.
.
.
.
Please let me know how to go about this because I cannot pass my spec tests with this error. If anyone has any suggestions or insight I would greatly appreciate them.Thank you.

Controller file name should be users_controller.rb
As you mentioned in comment you don't have any User model defined. To create model run rails g model user name:string email:string. This will create User model with attributes name and email.
Try Rails scaffolding and see what files it creates(in controller, model and views ignore other files for now) and see the contents of those files. To use scaffold for creating User is as below:
rails g scaffold user name:string email:string
rake db:migrate

Related

NameError - wrong constant name when creating user (Devise, Rails)

I'm using Rails 5.0.5 with Devise 4.3.0 for authentication. This app has been running smoothly for months, until I added a 'type'=>'string' attribute to my User model and attempted to create a new user. Submitting the form gives me a 500 internal server error. In this example, the User.type = 'hunter'.
NameError - wrong constant name hunter:
activesupport (5.0.5) lib/active_support/inflector/methods.rb:268:in `const_get'
activesupport (5.0.5) lib/active_support/inflector/methods.rb:268:in `block in constantize'
activesupport (5.0.5) lib/active_support/inflector/methods.rb:266:in `each'
activesupport (5.0.5) lib/active_support/inflector/methods.rb:266:in `inject'
activesupport (5.0.5) lib/active_support/inflector/methods.rb:266:in `constantize'
activesupport (5.0.5) lib/active_support/dependencies.rb:583:in `get'
activesupport (5.0.5) lib/active_support/dependencies.rb:614:in `constantize'
activerecord (5.0.5) lib/active_record/inheritance.rb:177:in `find_sti_class'
activerecord (5.0.5) lib/active_record/inheritance.rb:209:in `subclass_from_attributes'
activerecord (5.0.5) lib/active_record/inheritance.rb:55:in `new'
devise (4.3.0) lib/devise/models/registerable.rb:20:in `new_with_session'
app/models/user.rb:58:in `new_with_session'
user.rb:
def self.new_with_session(params, session)
if session['devise.user_attributes']
new(session['devise.user_attributes']) do |user|
user.attributes = params
user.valid?
end
else
super
end
end
Is Rails think this attribute value is a ClassName?? Can't seem to figure this one out. Any help greatly appreciated.
ActiveRecord uses the type column for Single Table Inheritance (STI) by default and the type value is expected to name a class. Presumably you don't have a hunter class so you get a confusing NameError from deep inside the guts of ActiveRecord.
From the fine manual:
inheritance_column()
Defines the name of the table column which will store the class name on single-table inheritance situations.
The default inheritance column name is type, which means it's a reserved word inside Active Record. To be able to use single-table inheritance with another column name, or to use the column type in your own model for something else, you can set inheritance_column:
self.inheritance_column = 'zoink'
Either rename your type column to something else or tell ActiveRecord to use some other column name for STI:
class User < ApplicationRecord
self.inheritance_column = 'there_is_no_sti_here' # Or whatever you're not using for a column name.
end
Using self.inheritance_column = nil also works.
If you're doing this a lot then you could make it declarative by adding a concern:
module STISuppression
extend ActiveSupport::Concern
included do
self.inheritance_column = nil
end
end
and then say things like:
class SomeModel < ApplicationRecord
include STISuppression
end
Same effect but it makes it clear what you're up to.

Rails Puma Server: Undefined `extract_multipart' or `before_create' on logout action

I'm unable to logout out of my own page because I get a undefined method Puma error whenever I try. Most of the times it's extract_multipart, but I've also seen before_create.
This is what is shown in the blank page whenever I click logout
Puma caught this error: undefined method `extract_multipart' for Rack::Multipart:Module (NoMethodError)
/var/lib/gems/2.3.0/gems/rack-2.0.1/lib/rack/request.rb:472:in `parse_multipart'
/var/lib/gems/2.3.0/gems/rack-2.0.1/lib/rack/request.rb:335:in `POST'
/var/lib/gems/2.3.0/gems/rack-2.0.1/lib/rack/method_override.rb:39:in `method_override_param'
/var/lib/gems/2.3.0/gems/rack-2.0.1/lib/rack/method_override.rb:27:in `method_override'
/var/lib/gems/2.3.0/gems/rack-2.0.1/lib/rack/method_override.rb:15:in `call'
/var/lib/gems/2.3.0/gems/rack-2.0.1/lib/rack/runtime.rb:22:in `call'
/var/lib/gems/2.3.0/gems/activesupport-5.0.1/lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'
/var/lib/gems/2.3.0/gems/actionpack-5.0.1/lib/action_dispatch/middleware/executor.rb:12:in `call'
/var/lib/gems/2.3.0/gems/actionpack-5.0.1/lib/action_dispatch/middleware/static.rb:136:in `call'
/var/lib/gems/2.3.0/gems/rack-2.0.1/lib/rack/sendfile.rb:111:in `call'
/var/lib/gems/2.3.0/gems/railties-5.0.1/lib/rails/engine.rb:522:in `call'
/var/lib/gems/2.3.0/gems/puma-3.6.2/lib/puma/configuration.rb:225:in `call'
/var/lib/gems/2.3.0/gems/puma-3.6.2/lib/puma/server.rb:578:in `handle_request'
/var/lib/gems/2.3.0/gems/puma-3.6.2/lib/puma/server.rb:415:in `process_client'
/var/lib/gems/2.3.0/gems/puma-3.6.2/lib/puma/server.rb:275:in `block in run'
/var/lib/gems/2.3.0/gems/puma-3.6.2/lib/puma/thread_pool.rb:116:in `block in spawn_thread'
The way I'm managing log-outs is with
<%= link_to(logout_path, method: 'delete', class: 'dropdown-item') do %>
<!-- ... -->
<% end %>
Where the route is defined as delete 'logout' => 'sessions#destroy', and the controller / action is
def destroy
session[:id] = nil
redirect_to '/login'
end
The other error I have only caught once or twice and all I have is a screenshot
Puma: undefined before_create
Any ideas on what might be causing this? Thanks beforehand :)
Edit
As per request, here's the Enumerable concern, which I'm not actually using because I'm also having issues with that (GH issue submitted on auto-inc repository)
require 'autoinc'
module Enumerable
extend ActiveSupport::Concern
included do
include Mongoid::Autoinc
include Mongoid::Document
field :n, as: :number, type: Integer
increments :number
end
end
And the only before_create I'm using is within a completely unrelated module...
Edit 2
Tried updating puma to 3.7.0, didn't fix it. Although it didn't break it further...
Answer obtained from
Delete link sends "Get" instead of "Delete" in Rails 3 view
I needed to add the <%= csrf_meta_tag %> to my head.

Couldn't find ContentTemplate with 'id'=batch_stats

I have a route that looks like this:
get 'content_templates/batch_stats', to: 'content_templates#batch_stats', as: 'batch_stats'
when I invoke the following helper:
<%= link_to 'Statistics', batch_stats_path %>
I expect to go to the batch_stats action of content_templates controller.
def batch_stats
puts "Are we ever getting here??"
...
Unfortunately the action is never triggered. Rails blows up before it even gets to the controller:
ActiveRecord::RecordNotFound - Couldn't find ContentTemplate with 'id'=batch_stats:
activerecord (4.1.5) lib/active_record/relation/finder_methods.rb:320:in `raise_record_not_found_exception!'
activerecord (4.1.5) lib/active_record/relation/finder_methods.rb:420:in `find_one'
activerecord (4.1.5) lib/active_record/relation/finder_methods.rb:404:in `find_with_ids'
activerecord (4.1.5) lib/active_record/relation/finder_methods.rb:68:in `find'
activerecord (4.1.5) lib/active_record/querying.rb:3:in `find'
cancancan (1.9.2) lib/cancan/model_adapters/abstract_adapter.rb:20:in `find'
cancancan (1.9.2) lib/cancan/controller_resource.rb:116:in `find_resource'
cancancan (1.9.2) lib/cancan/controller_resource.rb:68:in `load_resource_instance'
cancancan (1.9.2) lib/cancan/controller_resource.rb:32:in `load_resource'
cancancan (1.9.2) lib/cancan/controller_resource.rb:25:in `load_and_authorize_resource'
cancancan (1.9.2) lib/cancan/controller_resource.rb:10:in `block in add_before_filter'
...
Why is this happening?
I figured it out.
I had two kinds of routes:
resources :content_templates do
get :show_template, on: :member
end
get 'content_templates/batch_stats', to: 'content_templates#batch_stats', as: 'batch_stats'
I got rid of the second one and just added a collection to first one:
resources :content_templates do
get :show_template, on: :member
get :batch_stats, on: :collection
end
And now it no longer looks for a member id.

o.respond_to?(:empty?) and o.empty? Fails with: "undefined method `empty?`"

so how is that possible?
I have a Module, that puts a Ruby Object at the end of the renderd page in a nice structured HTML. So i recurse through the given object and build the HTML output. The following is an excerpt of the code where the error is thrown.
EDIT:(had a copy error in code)
o=some object
nicer=if o.respond_to?(:empty?) and o.empty?
add_class='empty'
'empty ' + class_name
else
case o
when TrueClass then
"TRUE"
when FalseClass then
"FALSE"
when Array
#some more when's
the error thrown: undefined method 'empty?' for #Journey::Routes:0x123456
the object (o) it self is ActionDispatch::Routing::RouteSet
again: how is that possible?
EDIT: Stack: (there is the bad one ...)
actionpack (3.2.13) lib/action_dispatch/routing/route_set.rb:366:in `empty?'
lib/tech_draw.rb:90:in `format_nice'
lib/tech_draw.rb:101:in `block in format_nice'
lib/tech_draw.rb:100:in `each'
lib/tech_draw.rb:100:in `map'
lib/tech_draw.rb:100:in `format_nice'
lib/tech_draw.rb:124:in `block in format_nice'
lib/tech_draw.rb:123:in `map'
lib/tech_draw.rb:123:in `format_nice'
lib/tech_draw.rb:13:in `block in say'
lib/tech_draw.rb:13:in `map'
lib/tech_draw.rb:13:in `say'
lib/tech_draw.rb:13:in `map'
lib/tech_draw.rb:6:in `say'
app/controllers/home_controller.rb:131:in `any_page'
actionpack (3.2.13) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
...
How is that possible? Easy:
class Thing
def respond_to? *args
true
end
end
o = Thing.new
o.respond_to?(:empty?) and o.empty?
# => NoMethodError: undefined method `empty?' for #<Thing:0x00000100ae2558>
Although why is it happening in this case is another matter.
ActionDispatch::Routing::RouteSet#empty? appears to call empty? on routes object. Assuming this object is an instance of Journey::Routes that would explain the error, as Journey::Routes doesn’t have an empty? method. (In current Rails versions Journey is part of Rails itself, but in Rails 3.2 it is separate).
I don’t why this is happening in your case though.

NameError - uninitialized constant error in rails 4

I have the following code in my "ProgramsController.rb " file where, Im using a class called "DataTableDelegate" which is in a separate file called: "datatable_delegate.rb"
# GET /programs
# GET /programs.json
def index
puts "Running Program/index"
puts "Model name = #{controller_name.classify}"
respond_to do |format|
format.html
#datatable_options = generate_datatable_hash(view_context, controller_name.classify, Program.data_table_attribute_array )
log_with_blue("============================================")
log_with_yellow("#{#datatable_options.inspect}")
log_with_blue("============================================")
>>>>>> format.json { render json: DataTableDelegate.new( #datatable_options) }
end
end
The file "datatable_delegate.rb" is located at
app/datatables/datatable_delegate.rb
When I load the Programs url in the browser I get the following in my log:
Completed 500 in 237ms
NameError - uninitialized constant ProgramsController::DataTableDelegate:
activesupport (4.0.0) lib/active_support/dependencies.rb:500:in `load_missing_constant'
activesupport (4.0.0) lib/active_support/dependencies.rb:183:in `const_missing'
app/controllers/programs_controller.rb:22:in `block (2 levels) in index'
actionpack (4.0.0) lib/action_controller/metal/mime_responds.rb:191:in `respond_to'
app/controllers/programs_controller.rb:13:in `index'
actionpack (4.0.0) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
actionpack (4.0.0) lib/abstract_controller/base.rb:189:in `process_action'
......
I tried to put a require statement in my programs controller file but I still am getting the error.....
What should I do?
Thanks
You do not need the require statement in your ProgramsController as all files in the app/ directory are autoloaded by Rails.
The problem is the way you're accessing the DataTableDelegate. It is namespaced with Datatable, hence the placement of this file is in app/datatables/ directory.
Try with the following:
::Datatable::DatatableDelegate.new( #datatable_options)
Please note the case of characters in the module and class names above.
Rename your file to 'data_table_delegate.rb'. Also check whether the path app/datatables is in your autoload_paths.

Resources