Rails 3.2.1 хеш опций redirect_to не работает - PullRequest
0 голосов
/ 27 февраля 2012

Использование Rails: 3.2.1 , Ruby: ruby ​​1.9.3p0 (редакция 2011-10-30 33570) [i686-linux] .

My HelloController.rb # sign_in метод проверяет полученные учетные данные (значения-формы). Если проверка не удалась, он отображает login_page .

После успешной проверки выполняется проверка подлинности пользователяучетные данные Если учетные данные найдены правильно, перенаправьте на Games # index еще перенаправьте на "/ hello / login_page"

В моем случае следующие работы

redirect_to "/games" # works

, в то время как приведенный ниже не работает

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

В последнем случае отображается ошибка: URL: http://localhost:3000/hello/sign_in

        Output:
        Routing Error

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

Однако при использовании того же стиля параметров дляперенаправление из моего UsersController.rb # create метода, перенаправление работает нормально.

Также, если учетные данные не найдены правильными, хотя и проверены, мне нужно показать пользователю страницу входа с сообщением, котороеID пользователя / пароль не совпадают. В этом случае следующие работы

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

в то время какследующее не работает

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

Я хотел бы понять, в чем причина такого поведения.

Ниже приведен код, который у меня на месте:

rout.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 (сгенерированный скаффолдом контроллер)

    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

1 Ответ

0 голосов
/ 28 февраля 2012

Подробнее об именованных маршрутах вы можете прочитать в статье руководства по маршрутизации о маршрутизации .

  • Вы можете сделать что-то вроде redirect_to game_path(@game), чтобы настроить действие show для игрового контроллера, и
  • redirect_to games_path(notice: "Some notice..") для перенаправления на действие индекса с уведомлением.
...