dev
dev

Reputation: 1507

View says Users is nil, but psql shows I have users

I am trying to display all the users in a view. I am using Rails 4.1.0 on Ruby 2.1.1. I am also using Heroku.

When I run psql command 'select * from users' it shows 3 users. However, in the view it seems to think my @users variable is nil

This is what my view/controller/model look like:

view: (app/views/status/index.html.erb)

<% if current_user %>
  <h1>All users</h1>
  <% if @users.nil? %>
    users is nil
  <% else %>
    <% @users.each do |user| %>
    <%= user %>
    <% end %>
  <% end %>
  4
<% else %>
  <%= render 'welcome' %>
<% end %>

Controller: (app/controllers/users_controller.rb)

class UsersController < ApplicationController
  def index
    @users = User.all
  end
end

Model: (app/models/user.rb)

class User < ActiveRecord::Base
  class << self
    def from_omniauth(auth)
      provider = auth.provider
      uid = auth.uid
      info = auth.info.symbolize_keys!
      user = User.find_or_initialize_by(uid: uid, provider: provider)
      user.name = info.name
      user.avatar_url = info.image
      user.profile_url = info.urls.send(provider.capitalize.to_sym)
      user.save!
      user
    end
  end
  has_many :comments, dependent: :delete_all
end

Any help or or thoughts on what I am doing wrong would be great.

Upvotes: 0

Views: 78

Answers (1)

Prakash Murthy
Prakash Murthy

Reputation: 13057

For displaying list of User objects set in UsersController, the index view should be in the file named app/views/users/index.html.erb.

Not app/views/status/index.html.erb as you are using.

app/views/status/index.html.erb is not connected to the UsersController; so @users is nil there, and it is correctly showing the users is nil message.

Upvotes: 2

Related Questions