Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

undefined method `user_path'

I am trying to construct a users model manually (without using 'resources :users' in the routes.rb file). My routes.rb file looks like this:

match '/users/:id', :to => 'users#show'
match '/all_users', :to => 'users#index'

This is my index method in the users controller:

def index
  @title = "All users"
  @users = User.paginate(:page => params[:page])
end

This is my index view:

<h1>All users</h1>
<%= will_paginate %>
<ul class="users">
  <% @users.each do |user| %>
    <li>
      <%= link_to user.email, user %>
    </li>
  <% end %>
</ul>
<%= will_paginate %>

I get this error message when I hit localhost:3000/all_users:

undefined method `user_path'

I don't see where this is coming from.

EDIT:

Ok, I've discovered that changing 'user' to '@user' in the view makes it work:

<%= link_to user.email, @user %>

But I really don't understand the error message, or the real difference between 'user' and '@user'. Plus, clicking on the link created does not redirect to the user's page, it stays on localhost:3000/all_users.

like image 522
Bazley Avatar asked Feb 27 '11 23:02

Bazley


2 Answers

match '/users/:id', :to => 'users#show'  

should be

match '/users/:id', :to => 'users#show', :as => :user 

The :as parameter tells the router what to name the route as (You can then add _path or _url to whatever the :as parameter is).

Also, any time you link directly to an ActiveRecord model (e.g. link_to user.email, user), it will try to turn user into user_path.

like image 108
Dylan Markow Avatar answered Sep 19 '22 16:09

Dylan Markow


For everyone who using rails 4 in your routes.rb post '/users', :to => 'users#create', :as => :user and you controller render json: @user, status: :created, location: @user_path

like image 41
BilalReffas Avatar answered Sep 18 '22 16:09

BilalReffas