Devise error "undefined local variable or method `resource_class' " - ruby-on-rails

I have the same problem as here undefined local variable or method `resource_class' in devise . The issue is that the code was already set like the answers. Is it a route problem ? Should I look elsewhere?
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :set_locale
before_action :set_instances
before_action :configure_permitted_parameters, if: :devise_controller?
before_action :mixpanel
def set_locale
I18n.locale = params[:locale] || I18n.default_locale
end
def redirect_to_back
begin
redirect_to :back
rescue ActionController::RedirectBackError => e
redirect_to root_path
end
end
def set_instances
#new_event ||= Event.new(title: ".......", capacity: 50, start_date: Time.zone.now, start_time: Time.zone.now, end_time: Time.zone.now)
#featured_quizz ||= Questionnaire.where('featured IS TRUE')
end
helper_method :resource_name, :resource, :devise_mapping
protected
def resource_name
:user
end
def resource
#resource ||= User.new
end
def devise_mapping
#devise_mapping ||= Devise.mappings[:user]
end
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) << [:name, :firstname, :lastname, :phone]
devise_parameter_sanitizer.for(:account_update) << [:name, :firstname, :lastname, :image, :phone]
end
end
=> _links.html.slim
.row.text-center
.col-md-10.col-md-offset-1
- if devise_mapping.omniauthable?
- resource_class.omniauth_providers.each do |provider|
= link_to omniauth_authorize_path(resource_name, provider), class:"btn btn-fb btn-block callout callout-fb"
span.fa.fa-facebook-official<>
span Connectez vous avec #{provider.to_s.titleize}
undefined method `users_path' for #<#:0x007ff25695fce0>
Is it a syntax error in front ?
li = link_to "Votre Compte", resource, as: resource_name, url: session_path(resource_name), remote: true, data: { toggle: "modal", target: "#login-modal" }
or is it the block in my routes.rb =>
devise_for :users, :controllers => {
:registrations => "registrations",
:sessions => "sessions",
:confirmations => "confirmations",
:omniauth_callbacks => "callbacks" }
devise_for :admins
Thanks for your help

I don't think the problem is devise related : the Devise Readme makes no mention of creating routes for the model used in devise_for
the users_path helper method is enabled from config/routes.rb with the line :
get '/users', to: 'users#index', as: :users
or shortly, since you will probably need more routes :
resources :users, only: [:index] # you can skip the :only parameter if you need all restful routes.
Check Rails Routing from the Outside In for more information.

Related

Can't assign created_by as current_user. Database is saving as nil. Rails

I created a userstamps method to know which user created and edited a data. I have this table Illustrator that I am trying to assign created_by to the current_user id. But when it saves, created_by is nil and don't show any error. When I put raise right before illustrator.save, the #illustrator.created_by is exactly the current_user.id but when I check the value in db, is nil.
class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable,
:custom_authenticatable
belongs_to :account
belongs_to :role
cattr_accessor :current_user
validates :email, presence: true, uniqueness: true
validates :email, format: { with: URI::MailTo::EMAIL_REGEXP }
validates :password,
length: { minimum: 6 },
if: -> { new_record? || !password.nil? }
enum gen: { masculino: 1, feminino: 2 }
private
#apenas usuário com role de admim pode logar.
def valid_for_custom_authentication?(password)
#self.role.name == 'admin'
self.role_id === 2
end
end
class ApplicationController < ActionController::Base
before_action :authenticate_user!
helper_method :current_user
private
def current_user=(user)
#current_user = user
end
end
class IllustratorsController < ApplicationController
before_action :authenticate_user!
def new
#illustrator = Illustrator.new
end
def create
#illustrator = Illustrator.new(illustrator_params)
#illustrator.created_by = current_user.id
if #illustrator.save
redirect_to illustrator_path(#illustrator), notice: 'O autor foi criado com sucesso.'
else
render :new
end
end
private
def illustrator_params
params.require(:illustrator).permit(:name, :display_name, :email, :phone, :status, :notes, :created_by)
end
end
Rails.application.routes.draw do
get 'payments/index'
devise_for :users
root to: 'pages#home'
resources :books
resources :authors
resources :publishers
resources :illustrators
resources :plans do
resources :accounts, only: %i[new create] do
end
end
resources :payments, only: %i[index]
resources :accounts, only: %i[index show edit update destroy] do
resources :users, only: %i[new create] do
resources :roles
end
end
resources :users, only: %i[edit update index show destroy]
#API routes
namespace :api do
namespace :v1 do
get 'default/:id', to: 'plans#change_plans'
get 'plans', to: 'plans#index'
get 'plans/id', to: 'plans#show'
get 'accounts', to: 'accounts#return'
post 'users', to: 'users#create'
#resources :users
post '/auth/login', to: 'authentication#login'
get '/*a', to: 'application#not_found'
post 'password/forgot', to: 'users#forgot_password'
end
end
end
If you are using devise, you dont need this part:
helper_method :current_user
private
def current_user=(user)
#current_user = user
end
Where did you even find it? Remove it from your codebase!
With devise you don't need any getter or setter methods.
It can possibly be the reason it's not working for you.
If in application_controller you have the before_action :authenticate_user!, current_user method should work right out of the box!
As well you don't need to add the before_action :authenticate_user! again here
class IllustratorsController < ApplicationController
before_action :authenticate_user!
, because you already made it application-wide in application_controller.
Your create method is good. Try removing the abundancies and it should all work.
You have just setter method in your controller where you are setting current_user
def current_user=(user)
#current_user = user
end
You need to add getter method as well like following so that you can use it in your controller
def current_user
#current_user
end
In ruby there is short cut for this attr_accessor :current_user Ref this

rails 5 NoMethodError in RegistrationsController#new undefined method

Working on a course project and using rails 5 however the course isn't using rails 5 receiving this error after implementing this in NoMethodError in RegistrationsController#new
undefined method `<<' for nil:NilClass
was this before: class ApplicationController < ActionController::Base
class RegistrationsController < ApplicationController
before_action :configure_permitted_paramters, if: :devise_controller?
protected
def configure_permitted_paramters
devise_parameter_sanitizer.permit(:sign_up) << :fullname
devise_parameter_sanitizer.permit(:account_update) << :fullname << :cell_number << :license_plate_number << :vehicle_description << :email << :password
end
end
My routes changed to this as well part of the problem?
Rails.application.routes.draw do
root 'pages#home'
devise_for :users,
path => '',
:path_names => {:sign_in => 'login', :sign_out => 'logout', :edit => 'profile'},
controllers => {:omniauth_callbacks => 'omniauth_callbacks',
:registrations => 'registrations'
}
resources :users, only: [:show]
end
Your registration controller is redefining the Application Controller rather than defining the registration controller. Try the following:
class RegistrationsController < ApplicationController
def new
end
end

Rails devise undefined method `after_sign_in_path_for'

I have controller
class SessionsController < Devise::SessionsController
respond_to :js
layout false
def create
self.resource = warden.authenticate(auth_options)
if resource && resource.active_for_authentication?
sign_in(resource_name, resource)
end
end
end
and my template for it
create.js.erb
<% if user_signed_in?%>
<%= after_sign_in_path_for(resource) %>
<% else %>
Erorrs here...
})
<% end %>
I want redirect to specific page after sign in but have got
NoMethodError - undefined method `after_sign_in_path_for' for #<#<Class
what should i do to fix it?
Rails.application.routes.draw do
devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks",:confirmations => "confirmations",:passwords => "passwords", :sessions => "sessions" }
end
I have a similar implementation can you try this
class Devise::SessionsController < DeviseController
prepend_before_filter :require_no_authentication, :only => [ :new, :create ]
def create
self.resource = warden.authenticate(auth_options)
if resource && resource.active_for_authentication?
sign_in(resource_name, resource)
end
respond_with resource, :location => after_sign_in_path_for(resource)
end
end
In ApplicationController
private
def after_sign_in_path_for(resource)
stored_location_for(resource) || request.referer || root_path
end

cancan ability : allow site admin with rolify role create_user to create or sign_up new devise users

For the application, I am trying to implement job_code style access using cancan/cancancan, devise and rolify.
Only site admins with job_code :create_user will be able to create new users
Following is the code:
class RegistrationsController < Devise::RegistrationsController
before_filter :check_permissions, :only => [ :new, :create, :cancel ]
skip_before_filter :require_no_authentication
def check_permissions
authorize! :create, resource
end
end
class Ability
include CanCan::Ability
def initialize(user)
alias_action :create, :read, :update, :destroy, :to => :crud
if user.has_role? :create_user
can :create, User
end
if user.has_role? :create_annoucement
can :create, Announcement
end
end
end
in routes.rb, I have
devise_for :users ,:controllers => { :registrations => "registrations" }, :path_names => {:sign_in => "login", :sign_out => "logout"}, :path => "account"
Application Controller
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_action :authenticate_user!
check_authorization unless: :devise_controller?
before_filter :set_start_time if Rails.env.development?
before_action :configure_permitted_parameters, if: :devise_controller?
rescue_from CanCan::AccessDenied do |exception|
#https://github.com/ryanb/cancan/wiki/Devise
if current_user.nil?
session[:next] = request.fullpath
puts session[:next]
redirect_to new_user_session_path, :alert => "You have to log in to continue."
else
render file: "#{Rails.root}/public/403", formats: [:html], status: 403, layout: false
end
end
def set_start_time
#start_time = Time.now.usec
end
def configure_permitted_parameters
#devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:name, :email) }
devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:first_name, :last_name, :email, :password, :password_confirmation) }
devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:first_name, :last_name, :email, :password, :password_confirmation, :current_password, :user_manual) }
end
end
When I use, the following code in abilities.rb
if user.has_role? :create_user
can :create, :all
end
it works perfectly. It takes me to User sign_up page
but, when I have this code
if user.has_role? :create_user
can :create, User
end
it says Access Denied (403 page)
I am having a hard time to figure out, what should I use instead of User in can :create, User
I had to add :read along with :create permissions to access new/create actions, then parse down :read access

Override method of UsersController in Clearance

I want to change the
def url_after_create
'/'
end
of UsersController in Clearance. If I do this:
class UsersController < Clearance::UsersController
protected
def url_after_create
'/dashboard'
end
end
When I'm trying to sign up a new user, which works perfectly when not overriding, I get the following: The action 'index' could not be found for UsersController -- The action (post) is to '/users' and it seems that since the index action is not defined it fails. What should I do?
EDIT: Added code of Clearance::UsersController
class Clearance::UsersController < ApplicationController
unloadable
skip_before_filter :authorize, :only => [:new, :create]
before_filter :redirect_to_root, :only => [:new, :create], :if => :signed_in?
def new
#user = ::User.new(params[:user])
render :template => 'users/new'
end
def create
#user = ::User.new(params[:user])
if #user.save
sign_in(#user)
redirect_back_or(url_after_create)
else
flash_failure_after_create
render :template => 'users/new'
end
end
private
def flash_failure_after_create
flash.now[:notice] = translate(:bad_email_or_password,
:scope => [:clearance, :controllers, :passwords],
:default => "Must be a valid email address. Password can't be blank.")
end
def url_after_create
'/'
end
end
This line match ':controller(/:action(/:id(.:format)))' located in routes was causing the trouble. Commenting that solved it.

Resources