Rails - Devise - Add profile information to separate table - ruby-on-rails

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

Related

Can't add Company (from separate model) to Devise User

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

Query from database does not return in rails

My rails app has a User model and a Role model. Each User belongs to one role and each role has many users. There three methods defined in the user model to check the role of that user def admin?, def user?, and def expert?.
The User class:
class User < ActiveRecord::Base
mount_uploader :avatar, AvatarUploader
validates_presence_of :name
validates_presence_of :avatar
validates_integrity_of :avatar
validates_processing_of :avatar
before_save :assign_role
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
belongs_to :role
has_many :items
belongs_to :organization
has_many :expertkeywordmodels
has_many :keywords, through: :expertkeywordmodels
def assign_role
self.role = Role.find_by name: "Admin" if self.role.nil?
end
def self.with_role(role)
my_role = Role.find_by_name(role)
where(:role => my_role)
end
def admin?
self.role.name == "Admin"
end
def user?
self.role.name == "User"
end
def expert?
self.role.name == "Expert"
end
end
The Role class:
class Role < ActiveRecord::Base
has_many :users
end
I am trying to create a collection_select only with users that have expert role. Something like:
<%= collection_select(:keyword, :user_ids, User.where('expert?'), :id, :name, {prompt: true}, {:multiple => true}) %>
But it does not recognize expert? as a method. I was wondering if anyone knows how can I perform this query.
I am sorry if this is a naive question as I am new to rails.
Thanks,
Amir
User.where('expert?') doesn't really makes sense for the database, because it would translate to SQL like:
SELECT * FROM users WHERE expert?;
And obviously expert? isn't a valid SQL expression. expert? is only available in the context of your code.
Instead you need to write that logic in a way that translates to valid SQL and makes sense in the context of your database schema. My guess is that the following might work:
User.joins(:role).where(roles: { name: 'Expert'})
You might want to define a scope in your User model, like this:
scope :experts, -> { joins(:role).where(roles: { name: 'Expert'}) }
Than User.experts would return all users that have the expert role.
Not for nothing, but you have three methods in your user model that all set the same field, just differently.
def role(role_type)
self.role.name = role_type
end
To get your desired require to work properly - you can either write a scope or a method.
def get_roles(role_type)
User.role.name = role_type
end
Rail Guides are always extremely helpful. http://guides.rubyonrails.org/active_record_querying.html#passing-in-arguments

User roles with devise Modular Rails 4

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

How to let Users Be Apart Of A Group When They Sign Up for an Account

Hello I need help pushing users into groups when they sign up for an account. After a long hard day I have succeeded in adding the nested attribute of groups to users. But now when I submit my form I get this error...
ActiveRecord::AssociationTypeMismatch at /users Group(#70300311693200) expected, got ActionController::Parameters(#70300262460820)
Here are my models for the project
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
belongs_to :group
end
class Group < ActiveRecord::Base
validates :name, presence: true
has_many :users
default_scope lambda { order('groups.name') }
accepts_nested_attributes_for :users
end
Here is my nested attribute view
<div class="form-group">
<%= f.fields_for :group do |i| %>
<%= i.label :name %><br />
<%= i.select :name , Group.all.map { |c| [c.name, c.id] }%></p>
<% end %>
</div>
And here is my 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_filter :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:username, :email, :password, :first, :last, group: [:name, :id]) }
devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:username, :email, :last, :first, :current_password, :password, group: [:name, :id]) }
end
end
And Here is My Migration File
class CreateJoinTableUserGroup < ActiveRecord::Migration
def change
create_join_table :users, :groups do |t|
t.index [:user_id, :group_id]
t.index [:group_id, :user_id]
end
end
end
Update
class AddGroupIdToUser < ActiveRecord::Migration
def change
add_column :users, :group_id, :integer
end
end
All I need is to be able to check my rails console and be able to see if Users are Associated with a Group. If any one can tell me a quick method to do so I would greatly appreciate it. I am using rails 4.1.6 and devise.
You should have join table for this kind of concept.
As you are using devise for registration and other purpose. You need to override views and controller of devise to make desired changes. Because I think you should add feilds_for group on your sign_up form to add user in a group.
Providing you have a group_id foreign key on User which its value equal to to one of the Group's primary id, you should be able to test this relationship on rails console by typing
Group.first.users
OR
Group.find(ID).users
Refer to http://guides.rubyonrails.org/association_basics.html#the-has-many-association for more info about has_many association

Creating comments that belong to their respective microposts and users (in an app using Devise)

Right now, I have two models: User and Micropost.
The User model is working with Devise.
Example of the files involved:
user_controller.html.erb:
class PagesController < ApplicationController
def index
#user = current_user
#microposts = #user.microposts
end
end
index.html.erb:
<h2>Pages index</h2>
<p>email <%= #user.email %></p>
<p>microposts <%= render #microposts %></p>
microposts/_micropost.html.erb
<p><%= micropost.content %></p>
micropost.rb:
class Micropost < ActiveRecord::Base
attr_accessible :content
belongs_to :user
end
user.rg:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me
has_many :microposts
end
Now I want to create comments for the microposts:
Each comment should belong to its respective micropost and user (commenter). Not sure how to do this (is it a good situation to use polymorphic associations?).
An user should have many microposts and comments (not sure how to co this either).
I have no idea how to make it so that the comment is made the the user who is currently signed in (I think I have to do something with Devise's current_user).
Any suggestions to accomplish this? (Sorry, I'm a Rails beginner)
No, nothing you've said suggests that you need polymorphic associations. What you need is a comments model with a schema something like the following:
create_table :comments do |t|
t.text :comment, :null => false
t.references :microposts
t.references :user
t.timestamps
end
And then
# user.rb
has_many :microposts
has_many :comments
# microposts.rb
has_many :comments
You will probably want nested routes for your comments. So, in your routes.rb you'll have something like
#routes.rb
resources :microposts do
resources :comments
end
.. and in your comments controller, yes, you'll assign the value of comment.user something like the following...
# comments_controller.rb
def create
#comment = Comment.new(params[:comment])
#comment.user = current_user
#comment.save ....
end
You might want to look at the Beginning Rails 3 book, which would walk you through this.

Resources