Devise gem admin can add user into user model - ruby-on-rails

I am using devise gem for authentication in Rails. I want to create a admin dashboard that can add user into User model. I am able to render form into admin#index view, but I am not able to insert data in user model.
routes.rb
# when i use post method in this route i get routing error
get '/admin' => "admin#index", as: :create_user
Admin index.html.erb
<%= form_for User.new, url: create_user_path do |f| %>
<div class="log-in-form">
<h2 class="login-header text-center">Sign up</h2>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</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: "new-password" %>
</div>
<div class="field">
<%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation, autocomplete: "new-password" %>
</div>
<div class="actions">
<%= f.submit "Sign up" %>
</div>
<% end %>
admin_controller.rb
def index
end
def new
#user = User.new
end
def create
#user = User.new(user_params)
if User.save
redirect_to root_path
else
render :new
end
end
private
def user_params
params.require(:user).permit(:name,:password)
end

Sir, you badly need to read and understand this: https://guides.rubyonrails.org/routing.html
Answer:
You have defined the route as a get method yourself and you are expecting to post to it. Do you see something very odd here?
As a beginner, try not to deviate from basic CRUD routes that rails provides for you. In your case, do this in routes.rb:
resources :users
# OR:
# resources :users, only: %i[index show create update destroy]
# any names of CRUD functions that you probably will use (to avoid extra routes)
Now, in your html file change url: create_user_path to url: users_path.
BTW, at least make it a habit to check your routes in terminal like in your case: rails routes | grep user will give you the rails routes having word user in them.
It should work now.

Add following line in your config/routes.rb
post '/admin' => 'admin#index'

Related

Update information of different user with extension of Devise

I setup a platform that uses Devise to create and manage users and CanCanCan to manage permissions. Users have a role (admin or client) that allows them access to certain areas. Admin users have the ability to can :manage, :all
I extended Devise so that I have a users/registrations and users/sessions controller.
Admin users have access to views in a ManagerController dashboard that allows them to manage other users. I've figured out how to show the details of a different user, but I can't figure out how to save the information. I get errors that indicate it either can't find the User or that it requires a POST route.
I'm fairly new to Rails, so it could be something simple. I was able to find solutions that included the regular Devise installation, but not the extension. I feel like the problem may be in my routes.
I also can't create new users from here either.
Routes.rb
get 'users' => 'manager#users'
get 'users/edit' => 'manager#edit'
post 'users/edit' => 'manager#edit'
get 'users/new' => 'manager#new'
devise_for :users, :controllers => { registrations: 'users/registrations', sessions: 'users/sessions' }
devise_scope :user do
authenticated :user do
root 'users/registrations#edit', as: :authenticated_root
end
unauthenticated do
root 'users/sessions#new', as: :unauthenticated_root
end
end
Manager Controller
class ManagerController < ApplicationController
authorize_resource :class => false
include ManagerHelper
def users
#users = User.where.not(:id => current_user.id)
end
def new
#user = User.new
end
def create
#user = User.new(user_params)
if #user.save
flash[:notice] = "Successfully created User."
redirect_to root_path
else
render :action => 'new'
end
end
def edit
#user = User.find(params[:id])
#companies = Company.all
end
def update
#user = User.find(params[:id])
params[:user][:id].delete(:password) if params[:user][:password].blank?
params[:user][:id].delete(:password_confirmation) if params[:user][:password].blank? and params[:user][:password_confirmation].blank?
if #user.update(user_params)
flash[:notice] = "Successfully updated User."
redirect_to root_path
else
render :action => 'edit'
end
end
end
private
def user_params
params.require(:user).permit(:email, :first_name, :last_name, :company_id, :role, :password, :password_confirmation)
end
end
ManagerHelper
module ManagerHelper
def resource_name
:user
end
def resource
#resource ||= User.new
end
def devise_mapping
#devise_mapping ||= Devise.mappings[:user]
end
end
Manager/Edit.html.erb
<h2>Edit <%= resource_name.to_s.humanize %></h2>
<%= form_for(resource, :as => #user, :url => edit_user_registration_path(resource_name)) do |f| %>
<%= render "devise/shared/error_messages", resource: resource %>
<%= f.hidden_field :id %>
<div class="field">
<%= f.label :email %><br />
<%= f.email_field :email, autofocus: true, autocomplete: "email" %>
</div>
<div class="field">
<%= f.label :first_name %><br />
<%= f.text_field :first_name%>
</div>
<div class="field">
<%= f.label :last_name %><br />
<%= f.text_field :last_name %>
</div>
<div class="field">
<%= f.label :company %><br />
<%= f.collection_select :company_id, #companies, :id, :name, prompt: true %>
</div>
<div class="field">
<%= f.label :role %><br />
<%= f.text_field :role %>
</div>
<div class="field">
<%= f.label :password %> <i>(leave blank if you don't want to change it)</i><br />
<%= f.password_field :password, autocomplete: "new-password" %>
<% if #minimum_password_length %>
<br />
<em><%= #minimum_password_length %> characters minimum</em>
<% end %>
</div>
<div class="field">
<%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation, autocomplete: "new-password" %>
</div>
<div class="actions">
<%= f.submit "Update" %>
</div>
<% end %>
I would like the updated information to be saved to the User database.
Currently, I get this error when I click update after changing the user info.
ActiveRecord::RecordNotFound in ManagerController#edit
Couldn't find User without an ID
Weirdly, when I see the User info, the url is: http://localhost:3000/users/edit?id=2
But when I update (and get the error), the url changes to: http://localhost:3000/users/edit.user
I would also like to be able to create New Users from this screen.
Currently, the user form populates with the information of the user who is logged in. (To be fair, I have been trying to get the edit user correct before tackling this issue.)
I think You want to update existing user info.
If that is the case:
I find your url path is wrong
:url => edit_user_registration_path(resource_name)
you donot have to user registration here .
If the admin going to update info
in routes file . some thing like this
namespace :admins do
resources :users
end
then use the path creatd from this
Many tries later, I've found a solution. There were a lot of errors, so bear with me.
Routes.rb -- Was using the wrong URL in the form submission, so needed to add the routes for the Update function in the Manager controller.
get 'users/edit' => 'manager#edit'
post 'users/edit' => 'manager#edit'
get 'users/update' => 'manager#update'
post 'users/update' => 'manager#update'
Manager Controller -- I had to change the password rules so that I could update without a password. Similar concept, slightly different execution.
def update
#user = User.find(params[:user][:id])
#companies = Company.all
if params[:user][:password].blank? && params[:user][:password_confirmation].blank?
params[:user].delete(:password)
params[:user].delete(:password_confirmation)
end
if #user.update(user_params)
flash[:notice] = "Successfully updated User."
redirect_to root_path
else
render :action => 'edit'
end
end
Rendered Form.html.erb - Updated with newly created URL path.
<%= form_for(resource, as: #user, url: users_update_path(resource_name)) do |f| %>
<%= render "devise/shared/error_messages", resource: resource %>

reading parameters from create method

I have a ruby on rails project that is using the devise gem for authentication. I'm trying to use a captcha form in the sign up page to prevent bots from creating thousands of dummy logins
I'm not interested in using the recaptcha gem that works with devise as I haven't had any luck setting it up correctly.
I trying to set it up using this as a reference https://recaptchainrubyonrails.blogspot.com/
Here's my sign up page
<h2>Sign up</h2>
<%= form_for(resource, as: resource_name, url:
registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>
<div class="field">
<%= f.label :email %><br />
<%= f.email_field :email, autofocus: true, autocomplete: "email" %>
</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="g-recaptcha" data
sitekey="6LeeL5gUAAAAADbq0vt4d9biAs8oegkPx9ttUkKb"></div>
<div class="actions">
<%= f.submit "Sign up" %>
</div>
<% end %>
<br>
I do have my routes file point to a separate registrations controller instead of the one created within the devise registrations
devise_for :users, path: '', path_names: { sign_in: 'login', sign_out: 'logout' }, :controllers => {:registrations => "registrations"}
I can create a user regardless if I click on the captcha form. When I do click on it I get the parameter, g-recaptcha-response, in the create method that has a long text string such as
"g-recaptcha-response"=>"1234567890abcdefghi..."
I tried a create method that would look at that parameter and see if it is not nil. When it is nil I would like to back one page to the sign up page.
class RegistrationsController < Devise::RegistrationsController
def create
if not params[:g-recaptcha-response].present?
redirect_to :back
end
end
end
I can't even get to the parameter as it errors out saying
undefined local variable or method `recaptcha' for #<RegistrationsController:0x7219e5a0> Did you mean? catch"
I'm trying to capture this parameter, look at the value of g-recaptcha-response and somehow cancel the creation of a user if the response was nil or empty string
Alrighty, this is what I figured out that worked. Thanks to everyone who helped
#response = params[:"g-recaptcha-response"]
if #response == nil
flash[:notice] = "Please click on captcha form!"
redirect_back(fallback_location: new_user_registration_path)
else
flash[:notice] = "You signed up successfully!"
redirect_to root_path
end
Use 'g-recaptcha-response' instead of :g-recaptcha-response. You need to use string syntax because you cannot use - in symbol naming

Redirect_to(:back) in Rails after saving form to database causing routing errors

I am building a Rails from from scratch (without the use of Scaffold for the first time) to do a simple thing: submit to a database the username and a post.
To do that, in my Stories Controller, I have set up a create method:
class StoriesController < ApplicationController
def index
#posts = Post.where(slug: params[:id]).all
end
def create
#comments = Comment.new(params[:comments])
#comments.save
redirect_to(:back)
end
end
Then, in my view, I have this form in my Stories view:
<%= form_for :comments do |f| %>
<div class="form-group">
<div class="field">
<%= f.label :username %><br>
<%= f.text_field :username, class: "form-control" %>
</div>
</div>
<div class="form-group">
<div class="field">
<%= f.label :post %><br>
<%= f.text_area :post, class: "form-control" %>
</div>
</div>
<p>
<%= f.submit %>
</p>
<% end %>
What's weird is that when I click save, it fails to save to the table and has a routing error:
No route matches [POST] "/stories"
Troubleshooting
First off, I want to redirect back to the same page I was on, which has a URL like http://localhost:3000/stories?id=example-post-slug. I thought the routing error was weird, because shouldn't it just go back based on my controller code?
I also thought my routes.rb file could be an issue, but I have added it as a resource as other answers have suggested:
routes.rb
Rails.application.routes.draw do
resources :posts
resources :comments
get "stories" => "stories#index", as: :stories
....
end
Thus, I am confused. Why am I having a routing issue when I have defined the create method, added the Comments table as a resource, and I have chosen a redirect in my controller?

Couldn't find User with id=update_password with Devise

I'm using devise on a Rails application and for various reasons I needed to add a custom password change, using solution 3 from here: https://github.com/plataformatec/devise/wiki/How-To:-Allow-users-to-edit-their-password
I've looked through various other questions and tried augmenting my routes in a number of ways but the url always comes up /users/update_password (without a parameter passed), or /users/update_password.254 (with a parameter passed). I need it to be /users/254/update_password.
Here is the Users Controller I'm working with (relevant methods are update_password and user_params).
class UsersController < ApplicationController
inherit_resources
load_and_authorize_resource
before_filter :authenticate_user!
def destroy
name = #user.to_s
destroy!(notice: "User #{#user.to_s} was deleted.")
end
def edit
#user = current_user
end
def update_password
#user = User.find(current_user.id)
if #user.update_with_password(user_params)
sign_in #user, :bypass => true
redirect_to root_path
else
render "edit"
end
end
private
def build_resource_params
[params.fetch(:user, {}).permit(:name, :email, :phone_number, :password, :password_confirmation).tap do |p|
p[:institution_pid] = build_institution_pid if params[:user][:institution_pid]
p[:role_ids] = build_role_ids if params[:user][:role_ids]
end]
end
def build_institution_pid
institution = Institution.find(params[:user][:institution_pid])
authorize!(:add_user, institution)
institution.id
end
def build_role_ids
[].tap do |role_ids|
roles = Role.find(params[:user][:role_ids].reject &:blank?)
roles.each do |role|
authorize!(:add_user, role)
role_ids << role.id
end
end
end
def user_params
params.required(:user).permit(:password, :password_confirmation, :current_password)
end
end
This is the relevant portion of routes.rb
devise_for :users
resources :users do
collection do
get 'password'
put 'update_password'
end
end
This is the view I created to go with it:
<div class="page-header">
<h1>Change Password</h1>
</div>
<%= form_for(#user, :url => { :action => "update_password" } ) do |f| %>
<div class="field">
<%= f.label :password, "Password" %><br />
<%= f.password_field :password, :autocomplete => "off" %>
</div>
<div class="field">
<%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation %>
</div>
<div class="field">
<%= f.label :current_password %> <i>(we need your current password to confirm your changes)</i><br />
<%= f.password_field :current_password %>
</div>
<div class="action_container">
<%= f.submit %>
</div>
And this is the link: (currently with a parameter but I've tried without as well)
<li><%= link_to "Change Password", update_password_users_path(current_user) %></li>
When I click that link I get routed to a page that says ActiveRecord::RecordNotFound in UsersController#show, Couldn't find User with id=update_password.
I tried to follow the instructions pretty closely and I've tried to fiddle with the routes a couple times to get it to work and I'm pretty lost at this point. Has anyone seen this before and can help? Thanks!
To achieve what you need, you will have the following routes:
resources :users do
patch 'update_password', on: :collection
get 'edit_password', on: :member
end
Then you'll add a link that would lead user to update password form. The link should look like as follows:
<li><%= link_to "Change Password", edit_password_user_path(current_user) %></li>
The link would lead to users/edit_password.html.erb:
<div class="page-header">
<h1>Change Password</h1>
</div>
<%= form_for(#user, :url => { :action => "update_password" } ) do |f| %>
<div class="field">
<%= f.label :password, "Password" %><br />
<%= f.password_field :password, :autocomplete => "off" %>
</div>
<div class="field">
<%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation %>
</div>
<div class="field">
<%= f.label :current_password %> <i>(we need your current password to confirm your changes)</i><br />
<%= f.password_field :current_password %>
</div>
<div class="action_container">
<%= f.submit %>
</div>
<% end %>
When form is submitted, that would trigger update_password in UsersController. Here is the code for controller:
class UsersController < ApplicationController
def edit_password
#user = current_user
end
def update_password
#user = User.find(current_user.id)
if #user.update_with_password(user_params)
sign_in #user, :bypass => true
redirect_to root_url
else
render "edit_password"
end
end
private
def user_params
params.required(:user).permit(:password, :password_confirmation, :current_password)
end
end

How To Update User Profile to user authentication from scratch

I have followed the revised Railscast for user authentication from scratch.
I wanted to know how I can add in parts for user to modify profile as I have other fields that they need to enter after registering such as gender, ethnicity, career, about me, children, height, etc.
Is there a tutorial that shows you how to do this or can someone help point me in the right direction?
My project files can be viewed at https://github.com/pwz2k/date
UPDATE
I have started working on it, not sure if I am doing this right. I want the user to be able to modify their account settings (fields used when registering).
Below is my edit.html in the /users folder.
<h1>Account Information</h1>
<%= form_for #user do |f| %>
<% if #user.errors.any? %>
<div class="error_messages">
<h2>Form is invalid</h2>
<ul>
<% #user.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :email %><br/>
<%= f.text_field :email %>
</div>
<div class="field">
<%= f.label :password %><br/>
<%= f.password_field :password %>
</div>
<div class="field">
<%= f.label :password_confirmation %><br/>
<%= f.password_field :password_confirmation %>
</div>
<div class="field">
<%= f.label :username %><br/>
<%= f.text_field :username %>
</div>
<div class="field">
<%= f.label :zip_code %><br/>
<%= f.text_field :zip_code %>
</div>
<div class="field">
<%= f.label :birthday %><br/>
<%= f.text_field :birthday %>
</div>
<div class="actions"><%= f.submit %></div>
<% end %>
Here's my routes:
Dating::Application.routes.draw do
get 'signup' => 'users#new'
get 'login' => 'sessions#new'
get 'logout' => 'sessions#destroy'
get 'edit' => 'edit#edit'
resources :users
resources :sessions
resources :password_resets
root to: 'users#new'
And here is what I added to users_controller that I am not sure I did properly:
def edit
#user = User.find(params[:user])
end
def update
#user = User.find(params[:user])
if #user.update_attributes(params[:user])
flash[:success] = "Account updated"
sign_in #user
redirect_to #user
else
render 'edit'
end
How I will eventually have everything working is user will go to /edit to modify their account settings with all their private information that was filled our during registration. Then users can edit the profile information (gender, race, career, about me, etc) directly on their profile page (will use in-place editing). So I just need to know if the steps I have taken are correct (I haven't used the terminal yet) and if so how do I get the edit page to display as it shows routing error atm.
Just a few general pointers.
In the Railscasts the users_controller's new and create actions are being created. You'd like to edit a user, so you could build out the edit and update actions of this very controller.
# app/controllers/users_controller.rb
class UsersController < ...
def new
# exists
end
def create
# exists
end
def edit
# load the current_user; make sure a user can only edit his record!
end
def update
# save edit for the current_user, same security as above
end
end
In your routes you could figure out how to route a resource :profile singular resource (Rails guides) to map to the appropriate actions.

Resources