First-time poster, many-time finder-of-answers on the site (thank you!). I'm using Rails 5.2.3, ruby-2.6.2 and Devise gem 4.6.2. I have not been able to get an answer to work, even though there are plenty somewhat related questions here, here, here and here.
When a new User signs up, I want them to select their Company from a dropdown list (already created) in the sign-up form. (Eventually, this will be an admin role, but that's beyond the scope of this question.)
I created a registrations controller and added code per a number of the previous posts. Update, I was not extending Devise as I should have as indicated here: Extending Devise Registration Controller. This is my new Registrations controller.
class Users::RegistrationsController < Devise::RegistrationsController
before_action :configure_sign_up_params, only: [:create]
before_action :configure_account_update_params, only: [:update]
def new
#companies = Company.all
super
end
def create
#companies = Company.all
super
end
protected
def configure_sign_up_params
devise_parameter_sanitizer.permit(:sign_up, keys: [:company_id])
end
def configure_account_update_params
devise_parameter_sanitizer.permit(:account_update, keys: [:company_id])
end
end
And created new files in views/registrations with new.html.erb and edit.html.erb that I copied the exact code from the devise/registrations views.
I updated my routes.rb file to include:
devise_for :users, :controllers => { registrations: 'users/registrations', sessions: 'users/sessions' }
My User model is:
class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
belongs_to :company
accepts_nested_attributes_for :company
end
My Company model is:
class Company < ApplicationRecord
has_many :users
end
In the new user registration form, this works to provide the dropdown, but when I try to create the new user, it says: 1 error prohibited this user from being saved: Company must exist.
<%= f.collection_select :company, #companies, :id, :name, prompt: true %>
I thought this post would have the answer, but that appears to use Rails 3 and attr_accessible, which was deprecated in Rails 4.
I don't really understand what accept_nested_attributes_for :company does. The only thing in the Company model is the name.
Thank you in advance!
Welcome to StackOverflow.
In order to add more parameters to devise's sign up form, you'll need to sanitize the corresponding parameters using devise's sanitizer.
You should do that like this:
class ApplicationController < ActionController::Base
before_action :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:company_id])
end
end
You can find more information about parameter sanitizing and adding custom fields in this section of devise's readme
If you also want to add a select field including all the existing companies, you should add a collection select:
<%= f.collection_select :company_id, Company.all, :id, :name %>
Got it!
To extend the Devise controller, follow the help here: Extending Devise Registration Controller
The User models must also be updated to include the optional: true because here https://blog.bigbinary.com/2016/02/15/rails-5-makes-belong-to-association-required-by-default.html:
class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
belongs_to :company, optional: true
accepts_nested_attributes_for :company
end
Related
I'm trying to set up an age restriction when a user registers so that if they are too young they cannot register on an app i'm building.
I had to over-ride devise to allow me to pass through other values to the user (like :birth_date). However I also want to check the age of the user so that if they are too young, they cannot use the app.
What I have right here, in a rudimentary way it works, but it is not quite what I would like.
<%= f.input :birth_date, required: true, start_year:1999 %>
In my user model I created some methods that address the problem, however ultimately my problem is that none of this code is getting hit during the registration process, and that is what I need some help with. If someone could take a look at point me in the right direction, I would greatly appreciate it!
class User < ApplicationRecord
validate :age_restriction
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :cafes
def age_restriction
if (birth_date.to_date + 18.years) < Date.today # assuming dob format is mm/dd/yy
errors.add :birth_date, 'must be older than 18'
end
end
end
The controller I used to over-ride devise I called registration_controller and it is like so
class RegistrationsController < Devise::RegistrationsController
before_action :configure_sign_up_params, only: :create
before_action :configure_account_update_params, only: :update
protected
def configure_sign_up_params
devise_parameter_sanitizer.permit(:sign_up, keys: [:birth_date])
end
def configure_account_update_params
devise_parameter_sanitizer.permit(:account_update, keys: [:bith_date])
end
end
My initial controller was my user_controller. Initially I was hoping this would solve my issue, but after some more work realized I needed to over-ride devise (hence the other registrations_controller). I'll admit this may be what is causing me my issue, not sure though.
class UsersController < ActiveRecord::Base
def show
#user = User.find(params[:id])
end
def create
#user = current_user.build(user_params)
#user.save
end
private
def user_params
params.require(:user).permit(:birth_date)
end
end
Use validations.
There is a gem which adds some useful date validators:
https://github.com/adzap/validates_timeliness/
validates_date :date_of_birth, :before => lambda { 18.years.ago },
:before_message => "must be at least 18 years old"
You can use model validations to prevent a user instance from being created if the user does not meet the age restriction you have set:
User.rb
validate :age_restriction
def age_restriction
if (birth_date.to_date + 18.years) < Date.today # assuming dob format is mm/dd/yy
errors.add :birth_date, 'must be older than 18'
end
end
I am using Devise to build a registration/authentication system into my application.
Having looked at quite a few resources for adding information to the devise model (e.g. username, biography, avatar URL, et cetera..) [resources include Jaco Pretorius' website, this (badly formed) SO question, and this SO question.
That's all fine and well -- it works. But my problem is that it's saving to the User model, which, according to database normalizations (also referencing this SO question), it should in fact be saving to a sub-model of User which is connected via has_one and belongs_to.
Thus far, I have created a User model via Devise. I have also created a UserProfile model via the rails generate script.
user.rb (for reference)
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable, :confirmable, :recoverable, :rememberable, :trackable, :validatable
has_one :user_profile, dependent: :destroy
end
user_profile.rb
class UserProfile < ActiveRecord::Base
belongs_to :user
end
timestamp_create_user_profiles.rb
class CreateUserProfiles < ActiveRecord::Migration
def change
create_table :user_profiles do |t|
t.string :username, null: false
t.string :biography, default: ""
t.references :user, index: true, foreign_key: true
t.timestamps null: false
end
add_index :user_profiles, [:user_id, :username]
end
end
My question, now, is, how does one collect the information for both of these models and ensure, via the devise registration form, that it all ends up in the right places?
I've seen resources about creating state machines (AASM, and the answer to this SO question. I've also seen information about creating a wizard with WICKED, and an article on the same topic.
These all seem too complicated for my use-case. Is there some way to simply separate the inputs with devise and make sure the end up in the right place?
I think, instead of simply commenting on an answer that led me to the final answer, I'll archive the answer here in case someone in the future is trying to also find this answer:
I will be assuming that you have some sort of setup as I do above.
First step is you need to modify your User controller to accept_nested_attributes_for the profile reference as well as add a utility method to the model so when requested in code, the application can either retrieve the built profile model or build one.
The user model ends up looking like so:
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable, :confirmable, :recoverable, :rememberable, :trackable, :validatable
has_one :user_profile, dependent: :destroy
accepts_nested_attributes_for :user_profile
def user_profile
super || build_user_profile
end
end
Secondly, you will need to modify your sign up/account_update form to be able to pass the attributes for this secondary model into the controller and eventually to be able to build the profile for the parent model.
You can do this by using f.fields_for.
Add something like this to your form:
<%= f.fields_for :user_profile do |user_profile_form| %>
<%= user_profile_form.text_field :attribute %>
<% end %>
An example of this in my specific case is:
<%= f.fields_for :user_profile do |user_profile_form| %>
<div class="form-group">
<%= user_profile_form.text_field :username, class: "form-control", placeholder: "Username" %>
</div>
<% end %>
Finally, you will need to tell Devise that it should accept this new hash of arguments and pass it to the model.
If you have created your own RegistrationsController and extended Devise's, it should look similar to this:
class RegistrationsController < Devise::RegistrationsController
private
def sign_up_params
params.require(:user).permit(:email, :password, user_profile_attributes: :username)
end
end
(Of course, make the proper changes for your specific use-case.)
If you have simply added the Devise sanitization methods to your application controller, it should look similar to this:
class ApplicationController < ActionController::Base
before_filter :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) {|u|
u.permit(:email, :password, user_profile_attributes: :username)}
end
end
(Again, make the proper changes for your specific use-case.)
A small note on user_profile_attributes: :username:
Note this is a hash, of course. If you have more than one attribute you are passing in, say, as an account_update (hint hint), you will need to pass them like so user_profile_attributes: [:attribute_1, :attribute_2, :attribute_3].
Please check out the RailsCasts.com web-site.
There are a couple of interesting railscasts about nested model forms:
http://railscasts.com/episodes/196-nested-model-form-part-1
http://railscasts.com/episodes/197-nested-model-form-part-2
http://railscasts.com/episodes/196-nested-model-form-revised
Also check out accepts_nested_attributes_for
Or check out this question:
Profile model for Devise users?
Also note that for Devise 4.2 the '.for' method for the devise_parameter_sanitizer is deprecated in favor of '.permit'
From the documentation:
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_in) do |user_params|
user_params.permit(:username, :email)
end
end
I've been struggling with this issue for weeks. My goal is to create 3 different types of users. Regular, Page , Venue. Upon registration the user is able to select that role [Regular,Page or Venue]. depending on the role the user chooses they're redirected to a edit profile page where they have to fill in additional information. Depending on user role, the user is also provided with a specific layout and separate root.
Example : User chooses role via registration form once signed up the user is redirected to their edit form to fill in additional info like name, location. ( also trying to find a way to make that required, like before a user can interact with the platform they have to fill in additional information that was not required on the registration form. Any ideas on something for that would be amazing.)
so basically I would like to root the user by role to a specific view.
Also my application is being built within engines, using the modular wa
What I have now :
By following this tutorial I was able to set up the user roles very simply. and also wrapping my head around using cancan.
http://www.mashpy.me/rails/role-based-registration-with-devise-and-cancan-using-ruby-on-rails/.
User.rb
module M0ve
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
validates :user_name, presence: true, length: { minimum: 4, maximum: 12 }
validates :email, presence: true
validates :role, presence: true
has_many :posts, dependent: :destroy
has_many :comments, dependent: :destroy
ROLES = %w[regular page venue]
def role_symbols
[role.to_sym]
end
Application Controller
module M0ve
class ApplicationController < ActionController::Base
before_filter :authenticate_user!
protect_from_forgery with: :exception
protected
def after_sign_up_path_for(resource)
if current_user.role? :regular
regular_index
end
end
end
end
Registration Controller
module M0ve
class M0ve::RegistrationsController < Devise::RegistrationsController
private
def sign_up_params
params.require(:user).permit(:email, :user_name, :password, :password_confirmation, :role)
end
def account_update_params
params.require(:user).permit(:email, :user_name, :password, :password_confirmation, :current_password)
end
end
end
Routes
M0ve::Core::Engine.routes.draw do
devise_for :users, class_name: "M0ve::User",module: :devise,:controllers => { registrations: 'm0ve/registrations' }
resources :posts do
resources :comments
end
end
Sorry if I missed some information please let me know where I need to clarify and I'll appreciate any help .
You could use the Rolify gem with Devise and Cancan or Cancancan to manage multiple role based authorization.
With some effort you should be able to create and manage roles as well.
Use Cancan Gem
here is the link to it, the documentation is quite simple
https://github.com/ryanb/cancan
So I have an application that has a blog model,and a user model.
Now users can subscribe to many different blogs, and users can also create many of their own blogs.
What would the association look like?
Right now my models look like the following:
Blog.rb:
class Blog < ActiveRecord::Base
has_and_belongs_to_many :users
has_many :posts
end
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
has_and_belongs_to_many :blogs
validates :email, uniqueness: true, presence: true
validates_presence_of :password, on: :create
end
the user table has a blog_id:integer field, and the blog has a user_id:integer field.
Is this right?
And how would the commands work? I.E:
u = User.last
b = u.blogs.build(title: "bla")
b.user (shows the owner of the blog)
b.users (shows the users that have subscribed to the blog)
Ultimately, I'd like to allow users to subscribe to other peoples blogs, and create their own.
You are going to want to add a third model 'Subscriptions'. Then you are going to want to use the 'has_many_through:' association. Please read this section of the rails guides for a detailed example. http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association.
After you create the associations you are going to want to do something along these lines:
1) make sure you nest the 'subscriptions' routes underneath the blog route properly.
resources :blogs, only: [] do
resources :subscriptions, only: [:create, :destroy]
2) Create a _subscription.html.erb partial in app/views/subscriptions
3) Render the partial in blogs#show
<%= render partial: 'subscriptions/_subscription, locals: {blog: #blog}
4) Add the ability to add (create) a subscription in the partial: (this is only to add subscription, you will want to also add ability to remove)
<%= link_to [blog, Subscription.new], class: 'btn btn-primary', method: :post do %>
<i class="glyphicon glyphicon-star"> </i> Subscribe
<% end %>
5) Add 'create method' to subscriptions_controller.rb
def create
#blog = Blog.find(params[:blog_id])
subscription = current_user.subscriptions.build(blog: #blog)
if subscription.save
# Add code
else
# Add code
end
end
This should be enough direction to get you to the finish line. Good luck :)
I am currently using Rails 4 and Devise 3.0.0. I have tried to add a custom field of "Name" to the sign up form and edit registration form. Whenever I submit the form, the following errors arise:
Unpermitted parameters: name
WARNING: Can't mass-assign protected attributes for User: email, password, password_confirmation.
I understand that this has something to do with the way Rails 4 handles parameters, but I do not understand what I am supposed to do about it right now. I have searched around and have seen that I am supposed to add some lines to a User model involving "params."
My user model currently looks like this:
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable, #:recoverable,
:rememberable, :trackable, :validatable
attr_accessible :name, :password, :password_confirmation, :remember_me, :email
end
According to How is attr_accessible used in Rails 4?, I am supposed to add the following code to "The controller."
class PeopleController < ApplicationController
def create
Person.create(person_params)
end
private
def person_params
params.require(:person).permit(:name, :age)
end
end
What controller? And is this literal code? Since I am dealing with User, do I have to use User.create(user_params)? instead of Person.create(person_params)?
Rails 4 has moved parameter sanitisation to the Controller from the Model. Devise handles it for 3 actions, sign_in, sign_up and account_update. For sign_up, the permitted parameters are authentication key (which is :email by default), password and password_confirmation.
If you want to add :name to the User model and use it for sign_up, either change config.authentication_keys = [ :email ] to config.authentication_keys = [ :name ] in /config/initializers/devise.rb or, if you want to use both :email and :name, add this to the ApplicationController
class ApplicationController < ActionController::Base
before_action :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) << :username
end
end
Also check-
https://github.com/plataformatec/devise#strong-parameters
You have to add this in controller where you have written User.create(user_params). I am assuming that UsersController.
class UsersController < ApplicationController
def create
User.create(user_params)
end
private
def user_params
#assumption: user params are coming in params[:user]
params.require(:user).permit(:name, :age, :and_other_params_you_want_to_allow)
end
end
Yes, you should add one line which is like:-
attr_accessible :name
in your model to allow name to assigned and if it does not work try this How is attr_accessible used in Rails 4?
I have similar problem. So, to fix it I created custom registration controller inherit form DeviseRegistration controller. Check Devise documentation and define controller like this.
class RegistrationsController < Devise::RegistrationsController
before_filter :update_sanitized_params, if: :devise_controller?
def update_sanitized_params
devise_parameter_sanitizer.for(:sign_up) {|u| u.permit(:name, :email, :)}
end
end
Make sure you have define this routes for this controller in config/routes.rb
devise_for :users, :controllers => {:registrations => "registrations" } , :path => '', :path_names => {
:sign_in => 'login',
:sign_out => 'logout'
}
Check this documentation of devise for strong parameter.
i had similar issues, this was my fix:
class ApplicationController < ActionController::Base
before_filter :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:account_update) { |u| u.permit!}
end
end