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.
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 (eg link_to user.email, user
), it will try to turn user
into user_path
.
对于在您的routes.rb中使用rails 4的每个人post '/users', :to => 'users#create', :as => :user
和您的控制器render json: @user, status: :created, location: @user_path
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.