授權
給你一些觀點,你會尋找一些所謂authorization。
這是認證不同,因爲它與權限交易,而不是確定您的身份。我會在一分鐘內瞭解它如何工作。
解決您的問題,下面是你需要做什麼:
<%= link_to "Edit Profile", edit_user_path(current_user), class: "btn btn-primary btn-xs", if user_signed_in? && current_user == @user %>
我猜您是在一個user#show
動作,可以使用下面的代碼來調用這個:
#app/controllers/users_controller.rb
class UsersController < ApplicationController
def show
@user = User.find params[:id]
end
end
這意味着,如果你有以下途徑:
#config/routes.rb
resources :users
您將可以訪問@user
和current_user
。重要的是要注意current_user
!= @user
。儘管weezing
的回答很簡潔,但它並不驗證用戶是否擁有授權的;只是用戶認證
因此,你有幾種規格:
- 你需要知道,如果用戶在
- 實際登錄你需要確保你的
logged-in
用戶有授權編輯配置文件(IE是他們的)
我強烈建議您查看gems
的使用,如CanCanCan
或Pundit
。我會告訴你CanCanCan:
#app/models/ability.rb
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
can :edit, Article, id: user.id
end
end
#app/views/users/show.html.erb
<%= link_to "Edit", edit_user_path(@user) if can? :edit, @user %>
有一個great resource here。
非常感謝豐富。很有幫助。下次我會使用你建議的寶石之一。 – robb
有時候最好自己寫一些東西 - 特別是爲了學習的目的:) – weezing