Как остаться на той же странице в случае неудачной регистрации при использовании Devise? (Форма регистрации отображается на странице root) - PullRequest
0 голосов
/ 27 марта 2020

Я новичок в этом сообществе как вошедший в систему пользователь, но вы, ребята, уже несколько раз сохраняли его без входа. Большое спасибо за это.

Я также относительно новичок to Ruby -on-Rails.

Я два дня глючил, намереваясь отключить перенаправление, созданное devise ...

По сути, у меня есть домашняя страница, где отображается пользовательская форма регистрации с использованием form_for и разработки следующим образом:

<div class="signup">
    <div>
      <h2>Create a new account</h2>
      <p>It's quick and easy.</p>
    </div>

    <%= form_for(resource, as: resource, url: registration_path(resource)) do |f| %>
      <%#= f.error_notification %>

      <div class="form-styling">
        <div>
          <%= f.text_field :first_name,
                          required: true,
                          autofocus: true,
                          placeholder: "First Name",
                          label: false,
                          autocomplete: "off" %>

          <%= f.text_field :family_name,
                          required: true,
                          placeholder: "Family Name",
                          label: false,
                          autocomplete: "off" %>
        </div>
        <div>
          <%= f.text_field :username,
                          required: true,
                          placeholder: "Username",
                          label: false,
                          autocomplete: "off" %>
          <%= f.email_field :email,
                           required: true,
                           placeholder: "Email",
                           label: false,
                           autocomplete: "off" %>
        </div>
        <div>
          <%= f.password_field :password,
                              required: true,
                              hint: ("#{@minimum_password_length} characters minimum" if @minimum_password_length),
                              placeholder: "Password",
                              label: false,
                              autocomplete: "new-password" %>
          <%= f.password_field :password_confirmation,
                              required: true,
                              placeholder: "Password Confirmation",
                              label: false,
                              autocomplete: "new-password" %>
        </div>
        <div>
          <%= f.text_field :address,
                          required: true,
                          placeholder: "Neighbourhood",
                          label: false,
                          autocomplete: "off" %>
        </div>
        <div class="bottom-signup">
          <div class="sign-up-btn">
            <%= f.submit "Sign up" %>
          </div>
          <%- if devise_mapping.omniauthable? %>
            <%- resource_class.omniauth_providers.each do |provider| %>
              <%= link_to "Sign up with #{OmniAuth::Utils.camelize(provider)}", omniauth_authorize_path(resource_name, provider) %>
            <% end %>
          <% end %>
        </div>
      </div>

    <% end %>
  </div>

Эта форма функционирует в соответствии с пожеланиями, но , если один из параметров требуется Devise ложно (например: password_confirmation! = пароль), перенаправляет меня на : http://localhost:3000/users вместо http://localhost:3000/, где я хочу, чтобы форма отображалась.

Я понимаю, что это связано с платформой Devise, но мне не удается найти способ ее обойти ..

Я пытался изменить Devise RegistrationsController как таковой:

class Users::RegistrationsController < Devise::RegistrationsController
  # before_action :configure_sign_up_params, only: [:create]
  # before_action :configure_account_update_params, only: [:update]

  # GET /resource/sign_up
  # def new
  #   super
  # end

  # POST /resource
  def create
    build_resource(sign_up_params)
    if resource.save
      redirect_to products_path
    else
      redirect_to root_path
    end
    yield resource if block_given?
    if resource.persisted?
      if resource.active_for_authentication?
        set_flash_message! :notice, :signed_up
        sign_up(resource_name, resource)
        respond_with resource, location: after_sign_up_path_for(resource)
       else
        set_flash_message! :notice, :"signed_up_but_#{resource.inactive_message}"
        expire_data_after_sign_in!
        respond_with resource, location: after_inactive_sign_up_path_for(resource)
       end
     else
      clean_up_passwords resource
      set_minimum_password_length
      respond_with redirect_to: root_path(resource),
                   notice: resource.errors['current_password'][0]
     end
  end

  # GET /resource/edit
  # def edit
  #   super
  # end

  # PUT /resource
  # def update
  #   super
  # end

  # DELETE /resource
  # def destroy
  #   super
  # end

  # GET /resource/cancel
  # Forces the session data which is usually expired after sign
  # in to be expired now. This is useful if the user wants to
  # cancel oauth signing in/up in the middle of the process,
  # removing all OAuth session data.
  # def cancel
  #   super
  # end

  # protected

  # If you have extra params to permit, append them to the sanitizer.
  # def configure_sign_up_params
  #   devise_parameter_sanitizer.permit(:sign_up, keys: [:attribute])
  # end

  # If you have extra params to permit, append them to the sanitizer.
  # def configure_account_update_params
  #   devise_parameter_sanitizer.permit(:account_update, keys: [:attribute])
  # end

  # The path used after sign up.
  # def after_sign_up_path_for(resource)
  #   super(resource)
  # end

  # The path used after sign up for inactive accounts.
  # def after_inactive_sign_up_path_for(resource)
  #   super(resource)
  # end
end

Это мой ApplicationController * 1 032 *:

class ApplicationController < ActionController::Base
  before_action :authenticate_user!
  before_action :configure_permitted_parameters, if: :devise_controller?
  protect_from_forgery with: :exception
  include Pundit

  # Pundit: white-list approach.
  after_action :verify_authorized, except: :index, unless: :skip_pundit?
  after_action :verify_policy_scoped, only: :index, unless: :skip_pundit?

  # Uncomment when you *really understand* Pundit!
  # rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
  # def user_not_authorized
  #   flash[:alert] = "You are not authorized to perform this action."
  #   redirect_to(root_path)
  # end

  private

  def skip_pundit?
    devise_controller? || params[:controller] =~ /(^(rails_)?admin)|(^pages$)/
  end

  def configure_permitted_parameters
    # For additional fields in app/views/devise/registrations/new.html.erb
    devise_parameter_sanitizer.permit(:sign_up, keys: [:first_name, :family_name, :username, :address])

    # For additional in app/views/devise/registrations/edit.html.erb
    devise_parameter_sanitizer.permit(:account_update, keys: [:username])
  end

  def after_sign_in_path_for(resource)
    return products_path
  end

  def after_sign_up_path_for(resource)
    return products_path
  end
end

Это мои маршруты :

devise_scope :user do
    get "/sign_in" => "pages#home" # custom path to login/sign_in
    get "/sign_up" => "pages#home", as: "new_user_registration" # custom path to sign_up/registration
  end

  devise_for :users, controllers: {
    sessions: 'users/sessions',
    registrations: 'users/registrations'
  }

  root to: 'pages#home'

Я схожу с ума от этой штуки, но мне бы очень хотелось понять Devise. .

Дайте мне знать, если вам нужно что-нибудь еще.

Заранее спасибо!

Ответы [ 2 ]

0 голосов
/ 28 марта 2020

я снова.

У меня решена проблема с моим другом после довольно небольшой суеты.

Здесь идет путь, который позволяет отключите автоматическое c перенаправление на форму разработки и включите возможность установки своих собственных параметров и оставайтесь на пути root_path после ошибки входа в систему :

1) Добавьте эти строки в свой маршрутов для того, чтобы переопределить прямой обратный вызов к сгенерированным формам Devise и настроить ваше путешествие пользователя.

 devise_for :users, controllers: {
    registrations: 'users/registrations'
  }

Тем самым вы сообщаете Rails, что вы меняете переменные Контроллер Devise для регистраций.

2) В ваших контроллерах / users / registrations_controller.rb создайте новый метод create .

def create
    build_resource(sign_up_params)
    resource.save
    yield resource if block_given?
    if resource.persisted?
      if resource.active_for_authentication?
        set_flash_message! :notice, :signed_up
        sign_up(resource_name, resource)
        respond_with resource, location: after_sign_up_path_for(resource)
      else
        set_flash_message! :notice, :"signed_up_but_#{resource.inactive_message}"
        expire_data_after_sign_in!
        respond_with resource, location: after_inactive_sign_up_path_for(resource)
      end
    else
      clean_up_passwords resource
      set_minimum_password_length
      render "pages/home"
    end
  end

То, что я сделал здесь, было только изменить последнюю посылку с:

else
      clean_up_passwords resource
      set_minimum_password_length
      respond_with resource, :location => after_sign_in_path_for(resource)
    end

на

else
      clean_up_passwords resource
      set_minimum_password_length
      render "pages/home"
    end

3) Затем необходимо создать новый файл в папке lib с именем custom_failure.rb (в любом месте в папке lib работает отлично). В этом файле добавьте следующие строки:

class CustomFailure < Devise::FailureApp
  def redirect_url
    '/'
  end

def route
  '/'
end

  # You need to override respond to eliminate recall
  def respond
    if http_auth?
      http_auth
    else
      redirect
    end
  end
end

Здесь вы переопределяете ответ для исключения отзыва.

4) Затем внутри config / initializer / devise.rb you добавьте эти строки:

config.warden do |manager|
    manager.failure_app = CustomFailure
  end

По сути, здесь вы указываете devise посмотреть на файл custom_failure.rb, который вы только что создали в случае сбоя.

5) Наконец, в вашем config / application.rb добавьте следующие строки в ваш модуль:

config.autoload_paths << Rails.root.join('lib')

Здесь вы указываете Rails автоматически загружать вашу 'lib' папку и все файлы, которые находятся в них (этот шаг не является обязательным для всех пользователей, но мое приложение rails не загружало автоматически файлы 'lib').


Надеюсь, это помогло некоторые из вас.

Наслаждайтесь вашим кодом.

Best, Ist

0 голосов
/ 27 марта 2020

В методе, где вы проверяете, вошел ли он в систему, и когда вы получаете ложь, добавьте

Redirect_to login_page_path
...