繁体   English   中英

当前用户的个人资料页面的Rails路线

[英]Rails route for current user's profile page

我正在寻找有关为当前用户的个人资料页面创建路径的最佳方法的建议。 目前,我只有用户作为资源。 您可以转到/ users /:user_id来访问任何用户的个人资料页面。 我也有成员路线,例如/ users /:user_id / followers。 我希望能够使用路由/ profile和/ profile / followers将当前用户带到他们的个人资料页面。 因此,如果我的用户ID为5,则可以转到/ profile,它将带我到/ users / 5所在的页面。

注意:我也在使用devise

路线

  resources :users, only: [:show, :update] do
    member do
      get :following, :followers
    end
  end

users_controller

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

  def followers
    @user = User.find(params[:id])
    @title = "Followers"
    @users = @user.followers.active

    render 'show'
  end

  def following
    @user = User.find(params[:id])
    @title = "Following"
    @users = @user.followed_users.active

    render 'show'
  end

有没有办法可以使用用户控制器和相同的操作

在路线中添加

get 'profile', to: 'users#show'

在操作中,使用current_user代替User.find(params[:id]来查找用户。然后,您无需在路径中添加Id

show action您可以添加以下内容以同时使用两者。

if params[:id]
  user = User.find(params[:id])
else
  user = current_user
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM