0

通常のユーザー(管理者のみが作成できる)が新しい記事を作成できないように制限したいRuby on Railsでブログアプリを実装しています。この目的のために、次の article_controller.rb ファイルに befor_filter を入れました。UI でユーザーから作成ボタンを非表示にしましたが、通常のユーザーはブラウザのアドレス バーに入力して新しい記事を作成できます。以下のコードを使用すると、通常のユーザーは新しい記事のページに移動できませんが、「undefined method `is_admin? whenアドレスバーに打ち込みます 詳細については、ユーザー認証用のデバイスを実装しました。

class ArticlesController < ApplicationController
  before_filter :is_user_admin, only: [:new, :create]

  def is_user_admin
    unless  current_user.is_admin?
      :root 
      return false
    end
  end
end 



class ArticlesController < ApplicationController
  before_filter :is_user_admin, only: [:new, :create]

  def is_user_admin
    unless  current_user.is_admin?
      :root 
      return false
    end
  end

    def index
        @articles = Article.all(:order => "created_at DESC")
    end

    def show
      @article = Article.find(params[:id])
    end

    def new
      @article = Article.new
    end

    def create
      @article = Article.new(params[:article])
      @article.user_id = current_user.id
      @article.save
      redirect_to article_path(@article)
    end

    def destroy
      @article = Article.find(params[:id])
      @article.destroy
      redirect_to action:  'index'  
    end

    def edit
      @article = Article.find(params[:id])
    end

    def update
      @article = Article.find(params[:id])
      @article.update_attributes(params[:article])
      flash.notice = "Article '#{@article.title}' Updated!"
      redirect_to article_path(@article)
     end
end

applicaiton_controller.rb

class ApplicationController < ActionController::Base
    protect_from_forgery
      def after_sign_in_path_for(user)
         if current_user.is_admin?
             dashboard_index_path
         else
             :root
         end
      end

end

基本的に、通常のユーザー (管理者以外) を制限して、UI から記事を作成、更新、または削除するか (これは完了)、アドレスバーにアドレスを入力します。なぜこれを取得しているのか、これを回避するために何ができるのかわかりません。application_controller.rbファイルに上記のメソッドを書くべきですか?

4

3 に答える 3

2

ユーザーが管理者でない場合、コントローラーのアクションにアクセスできないように、おそらくユーザーをログインにリダイレクトする必要があります。したがって、次のようなことができます。

def is_user_admin
  redirect_to(action: :index) unless current_user.try(:is_admin?)
end 
于 2013-04-13T23:42:16.370 に答える
2

あなたcurrent_userは明らかにゼロです。

before_filter :authenticate_user!, :except => [:show, :index]ユーザーを認証するには、コントローラーの上部に配置する必要があります。

于 2013-04-13T23:24:14.443 に答える
0

権限を確認する前に、少なくともユーザーが存在することを確認してください。認証が必要なすべてのコントローラーにこのコードを追加することで、これを行うことができます。

 before_filter :authenticate_user!

これを行うと、常に現在のユーザーが存在するため、質問で指摘した方法でその許可を確認できます。

于 2013-04-14T00:10:58.180 に答える