dimanche 10 juillet 2016

Custom controller for Devise Registrations

I'm using Rails 3.2.22.2 and Devise 3.5.10 and I have two scopes, users and admin

I'm implementing Devise on a legacy code to keep things more maintainable. Auth is already working great, but I've got some problems implementing the registration part. Here's the code:

routes.rb:

devise_scope :users do
  get '/login'  => 'users/sessions#new'
  get '/logout' => 'users/sessions#destroy'
  get '/logout' => 'users/sessions#destroy'

  get '/users/register/:invitation_token' => 'users/registrations#new'
end

devise_for :users,
           controllers: {
             sessions: 'users/sessions',
             registrations: 'users/registrations'
           },
           path_names: {
             sign_in: 'login',
             sign_out: 'logout',
             sign_up: 'register'
           }

controllers/users/registrations_controller.rb

module Users
  # Devise user registration
  class RegistrationsController < Devise::RegistrationsController
    before_filter :configure_sign_up_params, only: [:create]

    def new
      @hide_dashboard = true
      super do |user|
        invitation = Invitation.find_by_token(params[:invitation_token])
        if invitation
          user.invitation_token = invitation.token
          user.email = invitation.invitee_email
        end
      end
    end

    def create
      super
    end

    protected

    def configure_sign_up_params
      devise_parameter_sanitizer.for(:user) do |u|
        u.permit(:age_over_13, :terms_of_service)
      end
    end
  end
end

models/user.rb

class User < ActiveRecord::Base
  devise :database_authenticatable, :async, :registerable, :recoverable,
         :rememberable, :trackable, :validatable, :confirmable, :lockable,
         :timeoutable, :encryptable

Now, the problem: When I hit /uses/registration it loads ok. But when I submit the form with an invalid data, it was supposed to reload #new template and show the errors, but I got this message:

No route matches {:action=>"show", :controller=>"profile", :user_id=>#<User>}

Looking at the code through pry, I saw that it's related to respond_with resource code on default Devise create method. I'm missing something or I do need to copy and edit all the #create method to make it work??

Aucun commentaire:

Enregistrer un commentaire