Reputation: 101
I'm trying to render a list of users in a html.erb page but getting the error that the user variable is undefined.
As I understand, for the view to adopt the @users variable it needs to be called in a controller that is linked to the route of the view. I've tried this below but I think I'm calling the controller wrong (and thus the index method that defines @users). How would I go about fixing this so that the partial will render with the list of users?
views/pages/contacts.html.erb:
<table class='table table-condensed'>
<thead>
<tr>
<th>Email</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<%= render 'contact', collection: @users, as: :user %>
</tbody>
</table>
views/pages/_contact.html.erb:
<%= content_tag :tr, id: dom_id(user) do %>
<td><%= user.email %></td>
<td>
<%= link_to 'Add Contact', [:new, :contactship, id: user], remote: true unless current_user.has_contactship?(user) %>
<%# or link_to 'Add Contact', new_contactship_path(id: user), remote: true %>
<%= link_to 'Accept Request', [:contactships, id: user], method: :post, remote: true if current_user.requested_contacts_with?(user) %>
<%= link_to 'Remove Request', [:contactship, id: user], method: :delete, remote: true if current_user.pending_contacts_with?(user) %>
<%= link_to 'Remove Friend', [:contactship, id: user], method: :delete, remote: true if current_user.contacts_with?(user) %>
</td>
<% end %>
routes.rb:
Rails.application.routes.draw do
resources :posts
resources :contactships, only: [:new, :create, :destroy]
devise_for :users
authenticated :user do
root "pages#my_circles", as: :authenticated_root
get "/app/views/pages/to_post.html.erb", to: "pages#to_post", as: "to_post"
get "/app/views/pages/my_vault.html.erb", to: "pages#my_vault", as: "my_vault"
get "/app/views/pages/my_settings.html.erb", to: "pages#my_settings", as: "my_settings"
get "/app/views/pages/contacts.html.erb", to: "pages#contacts", as: "contacts" #THIS ROUTE
end
root 'pages#home'
namespace :api, defaults: { format: :json } do
namespace :v1 do
resources :circles, only: [:index, :show, :create, :update, :destroy]
end
end
end
controllers/pages_controller.rb:
class PagesController < ApplicationController
def index
@users = User.all
end
Thanks!
Upvotes: 1
Views: 797
Reputation: 12847
class PagesController < ApplicationController
def index
@users = User.all
end
...
rename contacts.html.erb to index.html.erb
index.html.erb
<table class='table table-condensed'>
<thead>
<tr>
<th>Email</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<%= render partial: 'contact', collection: @users, as: :user %>
</tbody>
</table>
Upvotes: 2