2016-12-23 3 views
0

Я добавил роли своим пользователям, и после регистрации вы автоматически отправляете меня на домашнюю страницу. Я пробовал много вещей с этого сайта и прошлых вопросов, но ничего не работает. Может быть, я передумал, я здесь новый. По сути, я хочу, чтобы люди, которые подписались, чтобы выбрать свою роль, если они учитель, они идут, чтобы создать новый класс («классные комнаты # новый»), и студенты идут на выбор своего класса («classrooms # index»). Я создал отдельный контроллер регистрации, как это было предложено, и это не сработало.Проблемы с перенаправлением после регистрации с помощью Devise. Что делать?

Зарегистрируйтесь форму (new.html.erb)

<div class="authform"> 
    <%= form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => { :role => 'form'}) do |f| %> 
    <h2>Sign Up</h2> 
    <%= devise_error_messages! %> 
    <div class="form-group"> 
     <%= f.label :name %> 
     <%= f.text_field :name, :autofocus => true, class: 'form-control' %> 
    </div> 
    <div class="form-group"> 
     <%= f.label :email %> 
     <%= f.email_field :email, class: 'form-control' %> 
    </div> 
    <div class="form-group"> 
     <%= f.label :password %> 
     <%= f.password_field :password, class: 'form-control' %> 
    </div> 
    <div class="form-group"> 
     <%= f.label :password_confirmation %> 
     <%= f.password_field :password_confirmation, class: 'form-control' %> 
    </div> 
    <div> 
     <%= f.radio_button :role, 'student' %> 
     <%= label :role_student, 'Student' %> 

     <%= f.radio_button :role, 'teacher' %> 
     <%= label :role_teacher, 'teacher' %> 
    </div> 
    <%= f.submit 'Sign Up', :class => 'button right' %> 

    <% end %> 
</div> 

Вот мой контроллер регистрации:

class Devise::RegistrationsController < DeviseController 
    def after_sign_up_path_for(resource) 
    if params[:user][:role] == 'student' 
     redirect_to 'classroom#index' 
    elsif [:user][:role] == 'teacher' 
     redirect_to 'classroom#new' 
    end 
    end 
end 

Вот мой контроллер пользователи

class UsersController < ApplicationController 
    before_action :authenticate_user! 
    after_action :verify_authorized 
    before_filter :check_role 

    def show 
    @user = User.find(params[:id]) 
    authorize @user 
    @posts = @user.posts 
    end 

    def new 
    @user = User.new 
    authorize @user 
    end 

    def check_role 
    if params[:user][:role] == 'student' 
     redirect_to 'classroom#index' 
    elsif [:user][:role] == 'teacher' 
     redirect_to 'classroom#new' 
    end 
    end 

    def update 
    @user = User.find(params[:id]) 
    authorize @user 
    if @user.update_attributes(secure_params) 
     redirect_to users_path, :notice => "User updated." 
    else 
     redirect_to users_path, :alert => "Unable to update user." 
    end 
    end 

    def destroy 
    user = User.find(params[:id]) 
    # authorize @user 
    user.destroy 
    redirect_to users_path, :notice => "User deleted." 
    end 

    def create_user_type 
    end 

    private 

    def secure_params 
    params.require(:user).permit(:role) 
    end 
end 

Edit: Вот мои маршруты страница

Rails.application.routes.draw do 
    get 'students/new' 

    get 'classrooms/new' 

    get 'teachers/new' 

    devise_for :users 
    resources :users 
    get "edit_profile" => "devise/registrations#edit" 
    resources :posts 
    resources :teachers 

    post 'users/create_user_type' => 'users/create_user_type' 
    root to: 'visitors#index' 
end 

Я знаю, что есть повторяющийся код с проверкой ролей, я просто сливаясь ответы вместе (что не очень хорошо знаю)

+0

Попробуйте переместить 'after_sign_up_path_for' в' application_controller' и настройте маршруты соответствующим образом. – 31piy

ответ

0

использовать монтировку камень с binding.pry, чтобы проверить код & содержимое переменной.

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

user.teacher? 
user.student? 

вместо

params[''][''] 

атрибута ресурса настойчивый вместо содержимого Params

0

Я считаю, что ваш контроллер регистрации неверен. Если вы создаете свой собственный контроллер регистраций, вы хотите, чтобы переопределить контроллер регистраций от завещанию:

class RegistrationsController < Devise::RegistrationsController 
def after_sign_up_path_for(resource) 
    if params[:user][:role] == 'student' 
    redirect_to 'classroom#index' 
    elsif [:user][:role] == 'teacher' 
    redirect_to 'classroom#new' 
    end 
end 
end 

Тогда в маршрутах вы должны убедиться, что он также использует свой собственный контроллер регистрации:

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

Надеюсь, это вам поможет.

Смежные вопросы