Разработать с помощью рельсов 4 аутентифицированного корневого маршрута, не работающего

Что я пытаюсь сделать

Я хочу отправить пользователя на новую страницу регистрации #, если они не вошли в систему.

После того, как вы введете регистрационную информацию и нажмите "Отправить", я хочу, чтобы вы были отправлены на страницу показа регистраций.

Что происходит

Он отправляет вас на новую страницу регистрации #, когда вы не вошли в систему (верно до сих пор). Но когда вы отправляете форму входа, она отправляет ошибки с помощью цикла переадресации. Вывод сервера повторяется снова и снова:

Started GET "/" for 127.0.0.1 at 2013-09-25 02:31:59 -0400
Processing by RegistrationsController#new as HTML
  User Load (0.7ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 8 ORDER BY "users"."id" ASC LIMIT 1
Redirected to http://lvh.me:3000/
Filter chain halted as :require_no_authentication rendered or redirected
Completed 302 Found in 2ms (ActiveRecord: 0.7ms)

Я не могу понять это. Он регистрирует вас, поскольку я вижу, что вручную перейдя на другую страницу, но корневой путь authenticated работает некорректно. Я пробовал несколько разных комбинаций в файле маршрутов и, похоже, не смог его получить. Код, который я использую, основан на этот поток

Мой код

В моем контроллере приложений у меня есть before_filter :authenticate_user!

Мой файл маршрутов:

devise_for :users, :controllers => {
  :registrations => "registrations"
}

devise_scope :user do
  root to: "registrations#new"
end

authenticated :user do
  root to: "registrations#show", :as => "profile"
end

unauthenticated do
  root to: "registrations#new", :as => "unauthenticated"
end

Ответы

Ответ 1

Сначала вы должны настроить Devise::RegistrationsController (вы можете добавить файл app/controllers/registrations_controller.rb)

И посмотри prepend_before_filter в разработке registrations_controller.rb

prepend_before_filter :require_no_authentication, :only => [ :new, :create, :cancel ]
prepend_before_filter :authenticate_scope!, :only => [:edit, :update, :destroy]

Добавьте show действие в prepend_before_filter :authenticate_scope!

registrations_controller.rb

class RegistrationsController < Devise::RegistrationsController
  prepend_before_filter :require_no_authentication, :only => [ :new, :create, :cancel ]
  prepend_before_filter :authenticate_scope!, :only => [:edit, :update, :destroy, :show]

  # GET /resource/sign_up
  def new
    super
  end

  # POST /resource
  def create
    super
  end

  # GET /resource/edit
  def edit
    super
  end

  def update
    super
  end

  # DELETE /resource
  def destroy
    super
  end

  def show
  end


  protected

  def after_sign_up_path_for(resource)
    after_sign_in_path_for(resource)
  end

end

Также скопируйте представление devize registration (изменить и новый шаблон) на /app/views/registrations/ и вы можете сделать файл show.html.erb в папке /app/views/registrations/ для Страница профиля.

Для маршрутов проектирования выглядит так:

devise_for :users, :skip => [:registrations]

devise_for :users, :controllers => {
  :registrations => "registrations"
}

authenticated :user do
  devise_scope :user do
    root to: "registrations#show", :as => "profile"
  end
end

unauthenticated do
  devise_scope :user do
    root to: "registrations#new", :as => "unauthenticated"
  end
end

Наконец, вы должны установить "путь" в after_sign_in_path_for(resource) и after_sign_out_path_for(resource_or_scope) в файле application_controller.rb

class ApplicationController < ActionController::Base
  protect_from_forgery

  private

   def after_sign_in_path_for(resource)
     # After you enter login info and click submit, I want you to be sent to the registrations#show page
     profile_path
   end
   def after_sign_out_path_for(resource_or_scope)
     new_user_session_path
   end
end

Примечание. Я пробовал это (чтобы создавать примеры приложений), и он работает. См. Журнал при входе здесь и войдите в систему здесь

Ответ 2

Перенаправление на registration#new по умолчанию, так что все, что вам нужно сделать, это это (в файле маршрута):

devise_for :users, :controllers => {
  :registrations => "registrations"
}

devise_scope :user do
  root to: "registrations#show" # This is the root path of the user when you are logged in
end

unauthenticated do
  root to: "registrations#new", :as => "unauthenticated"
end

# I dont't think this part is neccesary... Try if it works without
authenticated :user do
  root to: "registrations#show", :as => "profile"
end

Ответ 3

Не используйте маршруты для выполнения заданий, принадлежащих контроллеру.

Чтобы перенаправить пользователя на определенную страницу после регистрации, используйте Devise встроенный after_sign_up_path_for и переопределите его.

class ApplicationController
  def after_sign_up_path_for(resource)
    faked_user_profile_path(resource)
  end
end

Для маршрутов я не очень хорошо знаю всех, кроме devise_for. Но для функции перенаправления этого переопределения должно быть достаточно.