<%= current_user.role %> evaluates to nothing in Rails 4 - ruby-on-rails

I'm making a Rails app and am trying to have the user's role displayed on a view. The code I am using for this is:
<%= current_user.role %>
Which does not evaluate to anything.
I am using devise for user registrations and my registration view is as follows:
<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>
<div class="login-field">
<%= f.email_field :email, :placeholder => "Email" %>
</div>
<div class="login-field">
<%= f.password_field :password, autocomplete: "off", :placeholder => "Password (8 character min)" %>
</div>
<div class="login-field">
<%= f.text_field :firstname, :placeholder => "First Name" %>
</div>
<div class="login-field">
<%= f.text_field :lastname, :placeholder => "Last Name" %>
</div>
<div class="login-field">
<%= f.text_field :phone, :placeholder => "Phone Number" %>
</div>
<%= f.select(:role, ['Role 1', 'Role 2', 'Both']) %>
<br>
<div><%= f.submit "Signup" , :class => "btn btn-success btn-lg" %></div>
<% end %>
<%= render "devise/shared/links" %>
I have a feeling that I am doing something wrong in the form submission but cannot figure out what it is. Any help is appreciated

You can put this at the top of your create action:
return render text: params.inspect # get what the form sended
and or
return render text: create_params # get what the values you permitted
This way you will get what the data your from sended and if it is what you expected.

You should override the sign_up_params in the Devise registration. Once you've created your RegistrationsController that inherits from Devise::RegistrationsController, you can override the sign_up_params:
class RegistrationsController < Devise::RegistrationsController
private
def sign_up_params
params.require(:user).permit(:first_name, :last_name, :email, :phone, :role ... any other attributes)
end
end
You would also need to change you routes.rb to point to the newly created controller:
devise_for :users, controllers: {registrations: 'registrations'}

Related

How to show validation errors for a login form when fields are empty on submit

I'm using the Devise gem for authentication and for the login form when I click on "Log in" with the fields blank I get the error "Invalid Email or password". I think it would be nice just like the registration form to have errors like "Name can't be blank" or "Email can't be blank" depending on the field that is blank. How can one achieve that?
Log in view
<h2>Log in</h2>
<%= form_for(resource, as: resource_name, url: session_path(resource_name), data: { turbo: false }) do |f| %>
<div class="field">
<%= f.label :email %><br />
<%= f.email_field :email, autofocus: true, autocomplete: "email" %>
</div>
<div class="field">
<%= f.label :password %><br />
<%= f.password_field :password, autocomplete: "current-password" %>
</div>
<% if devise_mapping.rememberable? %>
<div class="field remember">
<%= f.check_box :remember_me %>
<%= f.label :remember_me %>
</div>
<% end %>
<div class="actions">
<%= f.submit "Log in" %>
</div>
<% end %>
<%= render "devise/shared/links" %>
application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :authenticate_user!
before_action :update_allowed_parameters, if: :devise_controller?
def after_sign_up_path_for(_resource)
groups_path
end
def after_sign_in_path_for(_resource)
groups_path
end
protected
def update_allowed_parameters
devise_parameter_sanitizer.permit(:sign_up) do |u|
u.permit(:name, :email, :password, :password_confirmation)
end
devise_parameter_sanitizer.permit(:account_update) do |u|
u.permit(:name, :email, :password, :password_confirmation, :current_password)
end
end
end
Its pretty trivial to just add a client side validation which will provide immediate feedback if you want to:
# app/views/devise/sessions/new.html.erb
<h2>Log in</h2>
<%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>
<div class="field">
<%= f.label :email %><br />
<%= f.email_field :email, autofocus: true, autocomplete: "email", required: true %>
</div>
<div class="field">
<%= f.label :password %><br />
<%= f.password_field :password, autocomplete: "current-password", required: true %>
</div>
<% if devise_mapping.rememberable? %>
<div class="field">
<%= f.check_box :remember_me %>
<%= f.label :remember_me %>
</div>
<% end %>
<div class="actions">
<%= f.submit "Log in" %>
</div>
<% end %>
<%= render "devise/shared/links" %>`
The views in your application will take priority over those defined by the engine.
The reason why Devise doesn't actually use model validation at all for sessions is that models are not context aware and adding this feature would add a lot of complexity for very little gain.
Your model doesn't have a concept of "signing in" so if you called resource.valid? it will fire all the validations for creating a record like for example uniqueness of the email.
While you could do this by creating a form object or by overriding the controller method and adding the errors "inline" it provides very little additional value in safeguarding your application against bad user input which is what server side validations are primarily intendended to do (user feedback is the secondary purpose). YAGNI.

How to signup in two different pages with devise

I used devise inthe login system.I want create two new html under the registrations, which is two different roles' pages. And I want to go to that page by choosing roles in registrations/new, which is the original signup file. What should I do next?
my files order in the view/user/registrations: enter image description here.
edit.html.erb
new.html.erb
new_librarian.html.erb
new_student.html.erb
I want to signup in the new two pages through registrations/new
<!-- what i changed in the registrations/new -->
<h2>Sign up</h2>
<p>Sign up as a Student<%= link_to 'Student', users_registrations_new_student_path, :method => 'get' %></p>
<p>Sign up as a Librarian<%= link_to 'Librarian', users_registrations_new_librarian_path, :method => 'get'%></p>
<!-- what is in the registrations/new_student -->
<h2>Sign up</h2>
<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
<%= render "devise/shared/error_messages", adminv: resource %>
<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: "new-password" %>
</div>
<div class="field">
<%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation, autocomplete: "new-password" %>
</div>
<div class="field">
<%= f.label :select_role %><br />
<%= f.collection_select :role, User::ROLES, :to_s, :humanize %>
</div>
<div class="actions">
<%= f.submit "Sign up" %>
</div>
<% end %>
<%= render "devise/shared/links" %>
<!-- what i changed in the routes.rb -->
get 'users/registrations/new_librarian'
get 'users/registrations/new_student'
Could not find devise mapping for path "/users/registrations/new_student". This may happen for two reasons:
1) You forgot to wrap your route inside the scope block. For example: devise_scope :user do get "/some/route" => "some_devise_controller" end
2) You are testing a Devise controller bypassing the router. If so, you can explicitly tell Devise which mapping to use: #request.env["devise.mapping"] = Devise.mappings[:user]
You can achieve this by overriding the devise registration controller. In your overrided registration controller, in the new method once the user is saved,
#app/config/routes.rb
devise_for :users, :controllers => {:registrations => "registrations"}
# app/controllers/registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
def new
if #user.save!
if #user.role == "librarian"
redirect_to librarian_profile_path
elsif #user.role == "student"
redirect_to student_profile_path
end
end
end
end
You can define librarian_profile_path and student_profile_path in your routes
#app/config/routes.rb
get 'librarian/new' => 'librarian_profile#new', :as => 'librarian_profile'
get 'student/new' => 'student_profile#new', :as => 'student_profile'

RoR: Forgot Password & Sign In - in same page

I'm trying to put Forgot password field with the sign in page, but if user is not registered (and not in apps database), then it redirects to the original devise Forgot password page with errors (http://localhost:3000/users/password). How do I make the errors appear in the same page as the sign in page (http://localhost:3000/users/sign_in)?
In app/views/devise/sessions/new.html.erb file
<%= simple_form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>
<%= f.email_field :email, required: false, autofocus: true, placeholder: "Username" %>
<%= f.password_field :password, required: false, placeholder: "Password" %>
<%= f.button :submit, "Sign In", class: "btn btn-success btn-sm" %>
<div class="remember-forgot">
<div class="row">
<div class="col-md-6">
<%= f.input :remember_me, as: :boolean if devise_mapping.rememberable? %>
</div>
<div class="col-md-6 forgot-pass-content">
Forgot Password
</div>
</div>
</div>
<% end %>
<!-- where reset is -->
<div class="pass-reset">
<%= simple_form_for(resource, as: resource_name, url: password_path(resource_name), namespace: 'forgot', html: { method: :post }) do |f| %>
<%= f.error_notification %>
<label>Enter the email you signed up with</label>
<%= f.email_field :email, required: true, autofocus: true, placeholder: "Email" %>
<%= f.submit "Submit", class: "pass-reset-submit btn btn-success btn-sm" %>
<% end %>
</div>
So there's a javascript link where an input field will show up if a user forgets their sign in credentials.
apparently two forms for same object having same fields should not be one page, one should stay with the new page. but still i have tried your question, and following things needs to be done
1) I have to override the passwords controller for devise under user scope.
class Users::PasswordsController < Devise::PasswordsController
# GET /resource/password/new
def new
super
end
# POST /resource/password
def create
self.resource = resource_class.send_reset_password_instructions(resource_params)
if successfully_sent?(resource)
flash[:notice] = "sent password"
redirect_to :root
else
render "devise/sessions/new"
end
end
# GET /resource/password/edit?reset_password_token=abcdef
def edit
super
end
# PUT /resource/password
def update
super
end
protected
def after_resetting_password_path_for(resource)
super(resource)
end
# The path used after sending reset password instructions
def after_sending_reset_password_instructions_path_for(resource_name)
super(resource_name)
end
end
then my devise/sessions/new page will look like this(you can add the logic of showing form only when one clicks he forget password button. that should be simple. just add hide class and on click remove hide class.)
Log in
<%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>
<div class="field">
<%= f.label :email %><br />
<%= f.email_field :email, autofocus: true %>
</div>
<div class="field">
<%= f.label :password %><br />
<%= f.password_field :password, autocomplete: "off" %>
</div>
<% if devise_mapping.rememberable? -%>
<div class="field">
<%= f.check_box :remember_me %>
<%= f.label :remember_me %>
</div>
<% end -%>
<div class="actions">
<%= f.submit "Log in" %>
</div>
<% end %>
#assuming that devise_mapping has recoverable? option. you can also keep the below form in if condition
<h2>Forgot your password?</h2>
<%= form_for(resource, as: resource_name, url: password_path(resource_name), namespace: "forget", html: { method: :post }) do |f| %>
<%= devise_error_messages! %>
<div class="field">
<%= f.label :email %><br />
<%= f.email_field :email, autofocus: true %>
</div>
<div class="actions">
<%= f.submit "Send me reset password instructions" %>
</div>
<% end %>
need to tell the routes to use my my passwords controller.
devise_for :users, controllers: {
passwords: 'users/passwords'
}
These things will result in showing the errors under the user sign in form but the path will remain http://localhost:3000/users/password. why because we are rendering the page and not redirecting. render just show the views without going to the controller action. now even if one tries to send the errors messages to the sessions controller somehow(after overriding that controller as well) somehow like this
redirect_to new_user_session_path, :messages => resource.errors
still that wont help, why because in session#new we are re initializing the resource as it is new action and all the errors would be gone.
I'm not sure if this is satisfactory to you or if this is not even close to your requirements. i tried to cover all things. i would be glad if some credible or official sources will provide even better response. that would definitely increase my knowledge as well.

changing devise route after edit user page

I want my user to be able to go straight to the path subscriptions/new after landing on their edit user/update account page. can anyone help me as to how i would go about this. I have listed my routes below
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_filter :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:name, :email, :password) }
devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:name, :line1, :line2, :town, :county, :postcode, :password, :password_confrimation, :current_password)}
end
private
def after_sign_in_path_for(resource)
edit_user_registration_path(current_user) #basically whichever path you think meets your needs
end
routes.rb file
Rails.application.routes.draw do
resources :subscriptions, only: [:new, :create, :show, :destroy]
#gives standard routes
get 'content/fruit'
get 'content/veg'
get 'content/mix'
devise_for :admin_users, ActiveAdmin::Devise.config
ActiveAdmin.routes(self)
namespace :admin do
get 'dashboard/index'
end
devise_for :users, :controllers => {:registrations => 'devise/registrations'}
# devise_for :users
resources :products do
resources :orders, only: [:new, :create]
#tells rails needs product id number
end
# get 'pages/payment'
get 'home/about'
get 'home/contact'
get 'seller' => "products#seller"
get 'sales' => "orders#sales"
get 'static_pages/productlanding'
get "content/veg"
get "content/fruit"
get "content/mix"
get 'subscriptions/new'
Devise Registration Controller
class Devise::RegistrationsController < DeviseController
def update
set_flash_message :notice, :"message here" if is_flashing_format?
session[:user_return_to] = new_subscription_path
super
end
end
Edit form user
<h2>Edit <%= resource_name.to_s.humanize %></h2>
<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>
<%= devise_error_messages! %>
<div class="form-group">
<%= f.label :avatar, class: 'col-sm-2 control-label' %>
<div class="col-sm-6">
<%= f.file_field :avatar %>
</div>
</div>
<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>
<% if devise_mapping.confirmable? && resource.pending_reconfirmation? %>
<div class="form-group">
Currently waiting confirmation for: <%= resource.unconfirmed_email %>
</div>
<% end %>
<div class="form-group">
<%= f.label :password %> <i>(leave blank if you don't want to change it)</i>
<%= f.password_field :password, autocomplete: "off", class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :password_confirmation %>
<%= f.password_field :password_confirmation, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :current_password %> <i>(we need your current password to confirm your changes)</i>
<%= f.password_field :current_password, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :line1 %>
<%= f.text_field :line1, autofocus: true, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :line2 %>
<%= f.text_field :line2, autofocus: true, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :town %>
<%= f.text_field :town, autofocus: true, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :county %>
<%= f.text_field :county, autofocus: true, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :postcode %>
<%= f.text_field :postcode, autofocus: true, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :organization %>
<%= f.text_field :organization, autofocus: true, class: "form-control" %>
</div>
<div class="form-group">
<%= f.submit "Update", class: "btn btn-primary" %>
</div>
<% end %>
<h3>Cancel my account</h3>
<p>Unhappy? <%= button_to "cancel my account", registration_path(resource_name), data: { confirm: "Are you sure?" }, method: :delete, class: "btn btn-danger" %></p>
<%= link_to "Back", :back %>
You can change path on this method after_update_path_for(resource)
class Devise::RegistrationsController < DeviseController
## other devise stuff
protected
def after_update_path_for(resource)
new_subscription_path
end
end
If you have multiple devise model you can try this
class Devise::RegistrationsController < DeviseController
## other devise stuff
protected
def after_update_path_for(resource)
if resource.is_a?(DeviseModel1)
new_subscription_path
else
other_path
end
end
end
Or you can put them into application_controller.rb
You need to override update action of devise registration controller for this.
class Devise::RegistrationsController < DeviseController
def update
set_flash_message :notice, :"message here" if is_flashing_format?
session[:user_return_to] = new_subscription_path
super
end
end
In your routes :
devise_for :users, :controllers => {:registrations => 'devise/registrations'}
There should be another controller app/controllers/devise/registrations. Controller code above.
If you want to make custom message then it come from config/locales/en.yml:
en:
devise:
registrations:
destroyed: "my custom message."
updated: "my custom message"

Still getting "Current password can't be blank" in Registration Edit after following wiki

I worry the solution here will be woefully obvious, but I'm having trouble implementing the instructions on the Devise wiki (https://github.com/plataformatec/devise/wiki/How-To%3a-Allow-users-to-edit-their-account-without-providing-a-password)
I'm using Rails 4. After following the wiki, I'm still receiving "current password can't be blank". Here's my setup. Any assistance is much appreciated!
REGISTRATIONS_CONTOLLER.rb
class RegistrationsController < Devise::RegistrationsController
def update
#user = User.find(current_user.id)
successfully_updated = if needs_password?(#user, params)
#user.update_with_password(devise_parameter_sanitizer.for(:account_update))
# Rails 3: #user.update_with_password(params[:user])
else
# remove the virtual current_password attribute update_without_password
# doesn't know how to ignore it
params[:user].delete(:current_password)
#user.update_with_password(devise_parameter_sanitizer.for(:account_update))
# Rails 3: #user.update_without_password(params[:user])
end
if successfully_updated
set_flash_message :notice, :updated
# Sign in the user bypassing validation in case his password changed
sign_in #user, :bypass => true
redirect_to after_update_path_for(#user)
else
render "edit"
end
end
private
# check if we need password to update user data
# ie if password or email was changed
# extend this as needed
def needs_password?(user, params)
user.email != params[:user][:email] ||
params[:user][:password].present?
end
end
APPLICATION_CONTROLER.rb
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_filter :configure_permitted_parameters, if: :devise_controller?
def configure_permitted_parameters
devise_parameter_sanitizer.for(:account_update) do |u|
u.permit(:first_name, :last_name, :username, :email, :avatar, :password, :password_confirmation)
end
devise_parameter_sanitizer.for(:sign_up) do |u|
u.permit(:first_name, :last_name, :username, :email, :password, :password_confirmation)
end
devise_parameter_sanitizer.for(:sign_in) do |u|
u.permit(:username, :email, :password)
end
end
end
ROUTES.rb
ProjectFoo::Application.routes.draw do
devise_for :users, :controllers => { :registrations => "registrations",
:invitations => 'users/invitations' }
Note: I'm also using the devise_invitable gem
VIEWS/DEVISE/REGISTRATIONS/EDIT.html.erb
<h2>Edit <%= resource_name.to_s.humanize %></h2>
<%= image_tag #user.avatar.url(:square) %>
<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => { :method => :put, :class => 'form-horizontal' }) do |f| %>
<%= devise_error_messages! %>
<div class="span5">
<div class="control-group">
<%= f.label :email, :class => 'control-label' %>
<div class="controls">
<%= f.email_field :email, :autofocus => true, :class => 'text_field' %>
</div>
</div>
<div class="control-group">
<%= f.label :username, :class => 'control-label' %>
<div class="controls">
<%= f.text_field :username, :autofocus => true, :class => 'text_field' %>
</div>
</div>
<div class="control-group">
<%= f.label :first_name, :class => 'control-label' %>
<div class="controls">
<%= f.text_field :first_name, :autofocus => true, :class => 'text_field' %>
</div>
</div>
<div class="control-group">
<%= f.label :last_name, :class => 'control-label' %>
<div class="controls">
<%= f.text_field :last_name, :autofocus => true, :class => 'text_field' %>
</div>
</div>
<div class="control-group">
<%= f.label :twitter_handle, :class => 'control-label' %>
<div class="controls">
<%= f.text_field :twitter_handle, :autofocus => true, :class => 'text_field' %>
</div>
</div>
<div class="control-group">
<%= f.label :avatar, :class => 'control-label' %>
<div class="controls">
<%= f.file_field :avatar, :class => 'file_field' %>
</div>
</div>
</div>
<div class="span5">
<% if devise_mapping.confirmable? && resource.pending_reconfirmation? %>
<div>Currently waiting confirmation for: <%= resource.unconfirmed_email %></div>
<% end %>
<div class="control-group">
<%= f.label :password, :class => 'control-label' %>
<div class="controls">
<%= f.password_field :password, :autocomplete => "off", :class => 'password_field' %><br><i>(leave blank if you don't want to change it)</i>
</div>
</div>
<div class="control-group">
<%= f.label :password_confirmation, :class => 'control-label' %>
<div class="controls">
<%= f.password_field :password_confirmation, :class => 'password_field' %>
</div>
</div>
<div class="control-group">
<%= f.label :current_password, :class => 'control-label' %>
<div class="controls">
<%= f.password_field :current_password, :class => 'password_field' %><p><i>(we need your current password to confirm your changes)</i></p>
</div>
</div>
<%= f.submit "Update" %>
</div>
<% end %>
<div class="span11">
<hr>
</div>
<div class="span11">
<h3>Cancel my account</h3>
<p>Unhappy? <%= button_to "Cancel my account", registration_path(resource_name), :data => { :confirm => "Are you sure?" }, :method => :delete %></p>
<p><%= link_to "Back", :back %></p>
</div>
You have update_with_password twice. The second time should be update_without_password.
I had same problem for hours. In my particular situation I had many custom user attributes that could be updated from different partials. Make sure you at least add hidden fields - name and email - as required by needs_password?

Resources