For my current routing, the following ruby on rails code:
<%= link_to current_user.name, users_path(current_user) %>
which produces a link like the following:
<a href="/users.1">name</a>
In turn, Ruby on Rails has a hard time understanding this as it expects the 1
to be the format:
ActiveRecord::RecordNotFound in UsersController#show
Couldn't find User without an ID
Request
Parameters:
{"format"=>"1"}
Which doesn't exactly make sense for Rails to route it like that, since it much rather should be /users/1
. Trying this by hand, however, gives the following result:
Routing Error
No route matches "/users/1"
Having the ID entered per hand with an ?id= param, such as /users?id=1
, works fine.
The issue is, I don't understand where the users.id comes from, nor how to fix - my rout开发者_如何学Pythoning file looks like
routes::Application.routes.draw do
get "register" => "users#new", :as => "register"
get "login" => "sessions#new", :as => "login"
post "login" => "sessions#create", :as => "do_login"
get "logout" => "sessions#destroy", :as => "logout"
resource :users
root :to => "pages#welcome"
end
All actions but the one mentioned above work fine, though I'd like to find out why. rake routes
lays it out like the following:
users POST /users(.:format) {:action=>"create", :controller=>"users"}
new_users GET /users/new(.:format) {:action=>"new", :controller=>"users"}
edit_users GET /users/edit(.:format) {:action=>"edit", :controller=>"users"}
GET /users(.:format) {:action=>"show", :controller=>"users"}
PUT /users(.:format) {:action=>"update", :controller=>"users"}
DELETE /users(.:format) {:action=>"destroy", :controller=>"users"}
The issue here seems to be that users#show seems to have taken the place of users#index, which would be the correct thing to do for /users. Since this is all pretty much default routing with no custom routes in terms of the issue on hand, I'm quite clueless here. Any ideas?
Edit: The users#show code is as simple as:
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
end
end
You probably want your route to use resources :users
, not resource :users
.
Also, change your link_to
to use user_path
instead of users_path
:
<%= link_to current_user.name, user_path(current_user) %>
精彩评论