[英]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.