I want my admin to be able to create users of different roles, something that my normal view of registration does not do, but the default validation of devise gives me an error before it enters the page.
my admin controller is:
admin_controller.rb
class AdminController < ApplicationController
before_action :authenticate_user!
def index
request_hash = {
:name => params[:name],
:email => params[:email],
:role => params[:role],
:password => params[:password],
:password_confirmation => params[:password_confirmation]
}
@user = User.create!(request_hash)
@user.save
end
end
Aplicacion_controller.rb
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 :configure_permitted_parameters, if: :devise_controller?
def after_sign_in_path_for(resource)
session[:previous_url] ||
if current_user.role == "admin"
admin_index_path
else
jolex_index_path
end
end
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:name, :role])
devise_parameter_sanitizer.permit(:account_update, keys: [:name, :country])
end
end
Model: User.rb
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
view: index.html.erb // is only for now afterwards it will be another route
<%= form_for resource, as: resource_name, url: registration_path(resource_name) do |f| %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :email %><br />
<%= f.email_field :email, autofocus: true %>
</div>
<div class="field">
<%= f.label :password %>
<% if @minimum_password_length %>
<em>(<%= @minimum_password_length %> characters minimum)</em>
<% end %><br />
<%= f.password_field :password, autocomplete: "off" %>
</div>
<div class="field">
<%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation, autocomplete: "off" %>
</div>
<div class="field">
<%= f.select(:role) do %>
<% [['Admin', "admin"], ['User', "user"]].each do |c| -%>
<%= content_tag(:option, c.first, value: c.last) %>
<% end %>
<% end %>
</div>
<div class="actions">
<%= f.submit "Sign up" %>
</div>
<% end %>
I would like to know if I am on the right path or if there are better ways