2017-06-24 14 views
-2

私は2つのコントローラを持っている:pages_controllerとcharges_controllerレールで特定のページの前にアクションを作成するにはどうすればよいですか?

pages_controllerだけあります

class PagesController < ApplicationController 
    def show 
     render template: "pages/#{params[:page]}" 
    end 
end 

charges_controllerは私のroutes.rbを私のホームページに設定されたルートを持っている料金

を受け入れるために、基本的なストライプの情報を持っており、 :

get "/:page" => "pages#show" 

ビュー/ページに約8個のHTMLファイルがあります。

「products.html.erb」にはbefore_action認証ユーザーが1つだけ必要です。

ページコントローラに前のアクションを追加すると、すべてのページに影響します。いくつかのヒント、新しい開発者が必要です。

+1

あなたはそれ以下の回答からいくつかのソリューションチェック正しいものをフォローアップする素敵だろうがある見つけた場合/ some comments – widjajayd

答えて

0
class PagesController < ApplicationController 
    def show 
     if "#{params[:page]}" == "product" 
      your action here 
     end 
     render template: "pages/#{params[:page]}" 
    end 
end 

通常、新しい/表示/編集/更新の間で「同じコード」のためのコントローラ内部のbefore_actionに、あなただけの1ページのための特別なコードを必要とするので、私は、コマンドの前にすることができますそれを

1

をレンダリングする場合は、あなただけの必要があると思いますbefore_actionを使用して「products.html.erb」をレンダリングするアクションを1つ選択します。それはあなただけのshowアクションでレンダリングされた場合、それは次のようになります。

before_action :authenticate_user, only: [:show] 

あなたがそこに好きなあなたは好きなように多くのルートを追加することができます。

before_action :authenticate_user, only: [:show, :create, :destroy] 

Hereそれのためのドキュメントです。

+0

@haydenあなたはそれを把握しましたか? – George

0

before_actionを入力してonly:オプションを使用すると、フィルタを適用するアクションの配列を渡すことができます。あなたはそのフィルタは、あなたが確認するカスタムのプライベートメソッドを作成することができますが、

class PagesController < ApplicationController 
    before_action :authenticate_user!, only: [:show] 

    def show 
    render template: "pages/#{params[:page]}" 
    end 
end 
1

をスキップするアクション名を除くすべてのアクションに適用する場合は、アクションの配列を渡すためにskip:を使用することができ、別のオプションがありますparams[:page]のparamの値は、これはあなたがしたいかだけshow方法でフィルタの前に工夫authenticate_userを適用し、その後制限しないものであれば、のようなものによって:

class PagesController < ApplicationController 
    before_action :custom_authenticate_user!, only: :show 

    # remains equal 
    def show 
    render template: "pages/#{params[:page]}" 
    end 

    private 

    # only if params[:page] equal 'bla' then use the authenticate_user! 
    def custom_authenticate_user! 
    authenticate_user! if params[:page] == 'bla' 
    end 

はまた、これは簡単な方法で、 ifとthを使用するだけですparamsをチェックして、新しいメソッドを作成することなく、それを動作させるために、電子onlyオプション:

class PagesController < ApplicationController 
    before_action :authenticate_user!, only: :show, if: -> { params[:page] == 'bla' } 
関連する問題