2012-02-27 3 views
0

작동하지 해시 : 3.2.1 루비 : 루비 1.9.3p0 (2011-10-30 수요일 수정 33570)는 i686 리눅스].레일 3.2.1 redirect_to 옵션 레일 사용

가 자격 증명을 (폼 값) received.If의 유효성 검사가 실패의 유효성을 확인 방법 sign_in 내 HelloController.rb 번호, 그것은 login_page을 렌더링합니다.

검증이 성공하면

는 자격 증명이 올바른지 발견하는 경우 사용자 자격 증명이 이 작품

redirect_to "/games" # works 
다음 다른 로 리디렉션 게임 # 지수에 "/ 인사/login_page"내 경우

을 재 인증 아래 하나가 작동하지 않는 동안

redirect_to {controller:"games", action:"index"} # Doesn't work 
URL :

 Output: 
     Routing Error 

     No route matches [GET] "/hello/sign_in"  

그러나 내 UsersController.rb 번호에서 리디렉션 옵션의 같은 스타일을 사용 http://localhost:3000/hello/sign_in 잘 작동 리디렉션, 방법을 만들

후자의 경우는 나에게 같은 오류를 보여줍니다. 검증하지만 다음 동안, 나는이 작품

redirect_to "/hello/login_page", :notice => "User Id and Password don't match" # works 

다음 사용자에게 사용자 ID/암호가이 사건을 match.In하지 않는 메시지와 함께 로그인 페이지를 표시 할 필요가 또한

자격 증명이 올바른지 찾을 수없는 경우

,

redirect_to {controller:"hello", action:"login_page" notice: "User Id and Password don't match" } # Doesn't work 

작동하지 않습니다 나는 그런 행동 뒤에 이유가 무엇인지 이해하고 싶습니다.

routes.rb

MyGames::Application.routes.draw do 

    resources :users do 
    # Collection route 
    collection do 
     get 'register' # creates the register_users_url and register_users_path route helpers. 
    end 
    end 

    resources :games 

    get "hello/index" 
    get "hello/login_page" 
    post "hello/sign_in" 

end 

HelloController.rb (수동 생성 컨트롤러)

class HelloController < ApplicationController 

     skip_before_filter :require_login 
     skip_before_filter :require_admin_role 


     def index 
      # Show index page 
     end 


     def login_page 
     self.page_title = "Log In" 

     end 

     def sign_in 

     # Validates the credentials.If validation fails 
     # render "login_page" 

     # Once validation is successful, authenticates the user credentials 
     # If credentials found correct, redirect to Games#index 
     # else redirect to "/hello/login_page" 

     # In my case following works 

     # redirect_to "/games", while 

     # the one below does not work 

     # redirect_to {controller:"games", action:"index"} # Doesn't work 

     end 

     private 

     def page_title=(page_title) 
      @page_title = page_title 
     end 

    end 

GamesController :

다음 나는 자리에있는 코드입니다. rb (비계 -generated 제어기)

class GamesController < ApplicationController 

     # This is the only piece I have added 
     skip_before_filter :require_admin_role, :only => [:index] 

     # GET /games 
     # GET /games.json 
     def index 

     end 

     # GET /games/1 
     # GET /games/1.json 
     def show 

     end 

     # GET /games/new 
     # GET /games/new.json 
     def new 

     end 

     # GET /games/1/edit 
     def edit 

     end 

     # POST /games 
     # POST /games.json 
     def create 

     end 

     # PUT /games/1 
     # PUT /games/1.json 
     def update 

     end 

     # DELETE /games/1 
     # DELETE /games/1.json 
     def destroy 

     end 
    end 

UsersController.rb (비계 생성 제어부)

class UsersController < ApplicationController 

     skip_before_filter :require_login, :require_admin_role, :only => [:register, :create] 

     # GET /users 
     # GET /users.json 
     def index 

     end 

     # GET /users/1 
     # GET /users/1.json 
     def show 

     end 

     # GET /users/new 
     # GET /users/new.json 
     def new 

     end 

     # GET /users/register 
     def register 
     @user = User.new 
     end 

     # GET /users/1/edit 
     def edit 

     end 

     # POST /users 
     # POST /users.json 
     def create # Customized by me 

     @user = User.new(params[:user]) 

     @user.role = 0 if @user.role.nil? 

     action_identifier = params[:action_identifier] 

     is_valid = @user.valid? 
     validation_result_options = get_validation_result_options(is_valid, action_identifier) 

     if is_valid 
      @user.save(:validate => false) 

      validation_result_options[:id] = @user.id if action_identifier != registration_action_identifier 

      # Save the user ID in the session so it can be used in 
      # subsequent requests 
      session[:current_user_id] = @user.id 

      # In this case it works correctly, by redirecting to '/games' 
      # when 'registration' action is found. 
      # The returned options are { controller: "games", action: "index" } 
      # which becomes 
      # redirect_to { controller: "games", action: "index" } 

      redirect_to validation_result_options 
     else 
      render validation_result_options 
     end 

     end 

     # PUT /users/1 
     # PUT /users/1.json 
     def update 

     end 

     # DELETE /users/1 
     # DELETE /users/1.json 
     def destroy 

     end 

     private 

     def get_validation_result_options(is_valid, action_identifier) 
     if is_valid 
      options = case action_identifier 
         when registration_action_identifier 
         { controller: "games", action: "index" } 
         else 
         { action: "show", notice: 'User was successfully created.' } 
         end 
     else 
      options = case action_identifier 
         when registration_action_identifier 
          { action: "register" } 
         else 
          { action: "new" } 
         end 
     end 

     options 
     end 

     def registration_action_identifier 
     "registration" 
     end 
    end 

와 ApplicationController.RB (비계 생성 컨트롤러)

class ApplicationController < ActionController::Base 
     protect_from_forgery 

     # Reference: http://guides.rubyonrails.org/action_controller_overview.html#filters 
     before_filter :require_login 
     before_filter :require_admin_role 

     # private methods are accessible by sub-classes 
     private 


     def current_user 
     @_current_user ||= session[:current_user_id] && User.find_by_id(session[:current_user_id]) 
     end 

     def require_login 
     unless logged_in? 
      redirect_to controller: "hello", action: "login_page", notice: "You must be logged in to access this section" 
     end 
     end 

     def require_admin_role 
     unless is_admin? 
      redirect_to controller: "hello", action: "login_page", notice: "You must have admin role to execute this action" 
     end   
     end 

     def logged_in? 
     !current_user.nil? 
     end 

     def is_admin? 
     logged_in? && current_user.role == 1 
     end 

    end 

감사합니다,

Jignesh

+0

명명 된 경로를 사용해 보셨습니까? – Ekampp

답변

0

당신은 the rails guide's article about routing에 지정된 경로에 대한 자세한 내용을보실 수 있습니다.

    당신은 게임 컨트롤러의 show 액션을 대상으로 redirect_to game_path(@game) 같은 뭔가를 할 수
  • redirect_to games_path(notice: "Some notice..")
  • 는 통지 index 액션로 리디렉션합니다.
+0

RESTful 경로에 대한 game_path 등 사용할 수있는 헬퍼를 사용하여 문제가 발생합니다. 수동으로 만든 컨트롤러의 경우에만 오류가 직면하고 내 질문에 대한 redirect_to 메서드를 사용하여 해시 리터럴 향해입니다. 내 게시물 redirect_to { 컨트롤러 : "games", action : "index"} redirect_to "/ games"가 작동하는 동안 작동하지 않습니다. 해시 리터럴을 전달할 때 기능이 작동하지 않는 이유는 무엇입니까? API는이 메소드가 해시 http://api.rubyonrails.org/classes/ActionController/Redirecting.html#method-i-redirect_to를 허용 할 수 있음을 분명하게 명시합니다. 감사. –