User profile pages with devise - Routing to show a

2020-02-26 09:46发布

Authentication with devise and a separate controller (Users) that is a single 'show' action

class UsersController < ApplicationController
#before_filter :authenticate_user!

  def show
    @user = User.find(params[:id])

    respond_to do |format|
        format.html # show.html.erb
        format.xml { render :xml => @user }
    end
  end
end

So far the view (users/show.html.erb) only displays the username of the accessed profile

<%= @user.username %>

Routing also:

resources :users

I would like these profile pages to be publically accessible if they get a link to it/told the address, but also want a link available to a currently logged in user to visit his profile. My a snippet from my header:

<li><%= link_to "Profile", @user %></li>
<li><%= link_to "Settings", edit_user_registration_path %></li>
<li><%= link_to "Logout", destroy_user_session_path, method: "delete" %></li>

Currently, @user is just there to stop a routing error. I'm not entirely sure what to link to, have tried quite a few combinations but obviously my rails newbie mind is missing something extra I need to do. Any help is much appreciated!

(Rails 4, ruby 2.0.0)

Side note I would also like to, eventually, allow the link to a profile page to display the id + username in the format: #{id}-#{username} (instead of just being users/1 --> users/1-bbvoncrumb).

3条回答
Fickle 薄情
2楼-- · 2020-02-26 10:41

You just need to pass User instance as a parameter to link_to if you want it to link to given user's show page. So if you want to link to currently logged in user's profile in Devise, you just need:

<li><%= link_to "Profile", current_user %></li>
查看更多
看我几分像从前
3楼-- · 2020-02-26 10:45

If you want to see the current logged in users profile make sure you are logged in.

add the before_filter :authenticate_user! in users controller.

Then in header link <li><%= link_to "Profile", current_user %></li>

查看更多
地球回转人心会变
4楼-- · 2020-02-26 10:47

I think this may help you.

In "Rails routing from the Outside in",

For example, you would like /profile to always show the profile of the currently logged in user. In this case, you can use a singular resource to map /profile (rather than /profile/:id) to the show action.

match "profile" => "users#show", :as => 'profile'

<li><%= link_to "Profile", profile_path %></li>

That is for private profile page.

Since the public profile page will be different to private profile page, I would create a profiles controller to show public profiles.

查看更多
登录 后发表回答