Reputation: 5167
When i access http://localhost:3000/users, it gives me NoMethodError in Users#index
. The error is as follows:
NoMethodError in Users#index
Showing /Applications/XAMPP/xamppfiles/htdocs/rails_projects/TUTORIALS/todo/app/views/users/index.html.erb where line #2 raised:
undefined method `name' for nil:NilClass
Extracted source (around line #2):
1: <% @users.each do |user| %>
2: hello!! <% @user.name %>
3: <% end %>
Rails.root: /Applications/XAMPP/xamppfiles/htdocs/rails_projects/TUTORIALS/todo
Application Trace | Framework Trace | Full Trace
app/views/users/index.html.erb:2:in `block in _app_views_users_index_html_erb___3451413751309771876_2169723860_4451603425222664605'
app/views/users/index.html.erb:1:in `each'
app/views/users/index.html.erb:1:in `_app_views_users_index_html_erb___3451413751309771876_2169723860_4451603425222664605'
My model user.rb:
# Table name: users
#
# id :integer not null, primary key
# name :string(255)
# email :string(255)
# created_at :datetime
# updated_at :datetime
#
class User < ActiveRecord::Base
attr_accessible :name, :email
My view app/views/users/index.html.erb:
<% @users.each do |user| %>
hello!! <% @user.name %>
<% end %>
My controller app/controllers/users_controller.rb
class UsersController < ApplicationController
def index
@users = User.all
end
My routes.rb file has:
resources :users
All my tests pass (using rspec) including the test case in spec/controllers/users_controller_spec.rb:
describe "GET 'index'" do
it "should be successful" do
get 'index'
response.should be_success
end
end
When I access http://localhost:3000/users/1, it shows me the users perfectly. Codes in app/views/users/show.html.erb:
<p>
<b>Name:</b>
<%= @user.name %>
</p>
I have done rake db:test:prepare and I think the error is linked to the db or migrations. Any idea? Thanks!
Upvotes: 2
Views: 1616
Reputation: 7188
Shouldn't it be:
<% @users.each do |user| %>
hello!! <% user.name %>
<% end %>
user
, not @user
?
Upvotes: 1
Reputation: 43298
This is incorrect:
<% @users.each do |user| %>
hello!! <% @user.name %>
<% end %>
It should be:
<% @users.each do |user| %>
hello!! <%= user.name %>
<% end %>
In your code the object @user
does not exist, that's why you get the error. In the iteration each user in @users
is put into the user
object one-by-one.
Another mistake in your code is that you were using <% @user.name %>
. This does not output anything. If you want to output the name of the user you have to use <%= user.name %>
(notice the equal sign).
Upvotes: 1