2015-10-14 71 views

回答

0

你是什麼尋找的是一種叫authorization

認證 =發現如果用戶存在

授權 = 確定它們是否能夠執行的具體要求

通過Sergei Stralenia的答案是正確的 - 你需要使用授權的寶石之一 - PunditCanCanCan是兩個最流行的 - 到驗證用戶是否能夠編輯特定的對象。

關於路由,除非將其分隔成類似於admin命名空間的東西(我將在第二個章節解釋更多內容),否則將無法刪除edit路由。

-

Sergei Stralenia的帖子展示瞭如何使用Pundit,我會告訴你CanCanCan

#app/models/ability.rb 
class Ability 
    include CanCan::Ability 

    def initialize(user) 
    user ||= User.new # guest user (not logged in) 
    if user.admin? 
     can :manage, Post 
    else 
     can :read, Post 
    end 
    end 
end 

#app/controllers/posts_controller.rb 
class PostsController < ApplicationController 
    def edit 
    @article = Post.find params[:id] 
    authorize! :edit, @article 
    end 
end 

聯繫

如果你想使一個帖子只有在「管理員」區域可編輯,你最好使用類似以下內容:

#config/routes.rb 
resources :posts, only: [:index, :show] 
namespace :admin do 
    resources :posts, only: [:new, :create, :edit, :update, :destroy] 
end 

這樣一來,你會從字面上沒有辦法對非管理員用戶在前端編輯/更新帖子。相反,他們必須進入admin區域,並使其能夠在其中編輯它...

#app/controllers/admin/posts_controller.rb 
class Admin::PostsController < ApplicationController 
    #actions & authorization in here 
end 
+0

謝謝! :)))))) – myf

0

在控制器上的編輯操作,執行相同的檢查 - 是這樣的:

@post = Post.find_by(id: params[:id]) 

unless @post.user == current_user 
    fail(ActionController::RoutingError, 'User cannot edit this post.') 
end 

可以簡化錯誤檢查分爲:

fail(ActionController::RoutingError, 'User cannot edit this post.') unless @post.user == current_user 

我希望這有助於!

1

使用權威寶石(https://github.com/elabs/pundit)是很好的可能性。 你的政策會看:

class PostPolicy 
    attr_reader :user, :post 

    def initialize(user, post) 
    @user = user 
    @post = post 
    end 

    def edit? 
    post.user == user 
    end 
end 

而且你的控制器的動作:

def edit 
    @post = Post.find_by(id: params[:id]) 
    authorize @post 
    ... 
end 
+0

謝謝! :)))))) – myf

0

我想這樣做是在你的帖子控制器使用before_filter最好的辦法,即:

before_action :authorize_admin, only: [:show, :edit, :update, :destroy] 

或:

before_filter :authorize_admin, except: [:show] 

其中:authorize_admin是,你必須定義或者在帖子控制器(用於僅職位),或在應用控制器(在所有控制器使用),這樣的方法:

def authorize_admin 
    redirect_to :new_user_session unless current_user&&current_user.admin? 
    end 
+0

謝謝! :)))))) – myf

相關問題