Creating a `Users` show page using Devise

喜夏-厌秋 提交于 2019-11-28 03:02:16

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!

you can generate the views used by devise, so you can change it as you want to.

 rails g devise:views
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!