Creating a `Users` show page using Devise
I'm trying to create a User show
page (that will function as a profile page) but am confused about how to do this with Devise. It doesn't seem as though Devise comes with any sort of show
definition - is there any way I can access the controllers Devise is implementing in order to m开发者_开发百科ake one or do I have to override them?
You should generate a users_controller
which inherits from application_controller
and define there your custom show
method. Don't forget to create a view and routes for it.
Ex:
#users_controller.rb
def show
@user = User.find(params[:id])
end
#in your view
<%= @user.name %>
#routes.rb
match 'users/:id' => 'users#show', via: :get
# or
get 'users/:id' => 'users#show'
# or
resources :users, only: [:show]
Don't forget that your users routes should be below the devise_for users routes, like this:
#routes.rb
devise_for :users
resources :users, :only => [:show]
Also, if you are using a username or an email as the primary key instead of the usual id, you should avoid routing conflicts by declaring your routes as follow:
#routes.rb
devise_for :users, :path_prefix => 'd'
resources :users, :only => [:show]
showing current_user/ other_user profiles with devise:
After installing devise
Create a Users controller:
rails generate controller Users
Then create a show action and find the user with params id:
def show
@user = User.find(params[:id])
end
Create a show.html.erb file in the User view folder:
<%= @user.email %>
Linking to users show page:
<%= link_to "current_user_show", current_user %>
Now if you want to view other profiles create a index action in the users controller:
def index @users = User.all end
Create an index.html.erb in the User view folder then:
<% @users.each do |user| %>
<%= link_to user.username, user %>
<%= user.email %>
<% end %>
The link for this will be:
<%= link_to "show_index_of_users", users_path %>
This will link you to the users index.html.erb file there you will create a loop and link to users profile:
<% @users.each do |user| %>
<%= link_to user.username, user %>
<%= user.email %>
<% end %>
This should work!
The users_controller.rb
should be outside of the devise
generated users
folder containing the sessions
and registration
controllers (if any).
# controllers/users_controller.rb
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
end
end
For your views:
# views/users/show.html.erb
<h1><%= @user.some_user_attribute_here %></h1>
and for your routes:
# config/routes.rb
get '/users/:id', to: 'users#show'
The show
route should also be separate from the custom devise
generated ones (if any).
you can generate the views used by devise, so you can change it as you want to.
rails g devise:views
精彩评论