Create "organization" automatically when user signs up? - ruby-on-rails-3

I'm using Devise for authentication with two custom fields added = :organization_id and :username. I also generated a scaffold for the Organization which simply consists of Name.
Currently when users sign up they can type in an Organization ID (integer) and a username (string).
Users belong_to organizations, and organizations has_many users.
Here's what my models look like (I left everything else untouched except for the files inside app/views/devise/registrations to add organization_id and username):
#user.rb
class User < ActiveRecord::Base
belongs_to :organization
# 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, :organization_id, :username
end
#organization.rb
class Organization < ActiveRecord::Base
has_many :users
end
What I would like is for an organization to be automatically created when a user signs up without the user having to specify the organization_id.
Also, ideally the #organization.name would be exactly the same as :username
How would I go about doing this?
I've seen the Railscast on nested model forms but he's creating a question inside the survey form, and questions belong to a survey. I need to do it the other way around (create an organization inside the user form, where users belong to a survey.)
Any help and suggestions would be greatly appreciated..

class User < ActiveRecord::Base
before_create :create_organization
private
def create_organization
self.organization = Organization.create :name => self.username
end
end
The create_organization method will be executed right before the sql query which creates the user. It'll create a new organization and assign it to the user.

Related

Rails Polymorphism for User modeling

I'm new to Rails 5 and I'm trying to model the following scenario using Devise and CanCanCan: a store application.
Relevant figures are: Admin, StoreManager, StoreOfficer, Customer, Technician.
Admin creates StoreManager.
StoreOfficer can create Customer's information to register new Customers.
StoreOfficer can see the complete list of all Customers with relative information
StoreOfficer can see the complete list of all Technicians with relative information
StoreManager can see the complete list of all StoreOfficers with relative information
StoreManager can enable StoreOfficers to use the system and edit their information
StoreManager can enable Customers created by StoreOfficers to use the system
StoreManager can see the complete list of all Customers with relative information
There are also some other paths, but it's possible for me to develop them as these presented cases are done.
Any help/tutorial please?
Thanks,
FZ
After trying some different things, I created the following satisfying schema, which I post here for others so that they can use something solid:
Class User<ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
belongs_to :userable, polymorphic: true
end
Then all the other roles classes similar to the following one:
class Customer < ApplicationRecord
belongs_to :technician
belongs_to :store_officer
has_one :user, as: :userable, dependent: :destroy
has_one :address, as: :addressable, dependent: :destroy
accepts_nested_attributes_for :user, :address
end
Accordingly, I created all the needed fields using migrations in the database.
Then I put in every controller the code before_action :authenticate_user!.
After populating the db a bit, I can now login with different users inserted using rake db:seed.
This is my routes.rb file:
Rails.application.routes.draw do
devise_for :users
resources :store_managers
resources :store_officers
resources :items
resources :technicians
resources :customers
resources :addresses
resources :users
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
What do you all think about this setup?
Now I want to introduce CanCanCan to my project. Please validate the following steps I'm going to do:
Run rails g cancan:ability
Put all the rules in the ability.rb file:
if user.admin?
can :manage, :all
elsif user.store_manager?
can :read, Customer
can :create, Customer
can :update, Item do |item|
item.try(:user) == user
end
can :destroy, Item do |item|
item.try(:user) == user
end
elsif user.store_officer?
can :read, Customer
end
.
.
.
Create the methods in user.rb model to check roles:
def customer?
self.userable_type == Customer
end
Put load_and_authorize_resource in every controller
Do you think this approach is the correct one? Or maybe I should put methods/definitions in other files?
Thanks,
FZ

Fetching all posts made by a user with Devise gem

I'm using Devise to manage user model.
Here's the User model, user.rb
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
acts_as_voter
has_many :topics
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
Here's the Topics model, topic.rb
class Topic < ActiveRecord::Base
acts_as_voteable
belongs_to :user
end
When I create a post, the user ID is stored in the "user_id" column of Topics. I want to a User profile page, which should display all the posts he has made. In my User profile page view, I have,
<%= Topic.find_by_user_id(#user.id) %>
I have two posts made by the same user,
But when I try fetch all the posts made by the user, the SQL command automatically queries with a LIMIT of 1. Like this,
And because of this, the view is fetching only 1 post made by the user. How do I fetch all the posts?
find_by_attribute will always return only one result. You need to change your code to:
Topic.where(user_id: #user.id)
or even better:
#user.topics

How can I format tags using acts-as-taggable-on gem before saving my user model?

How can I format tags using acts-as-taggable-on before saving the model?
I am using the following gem in my ruby on rails project
gem 'acts-as-taggable-on', '~> 2.3.1'
I have added interests tags to my user model.
user.rb
class User < ActiveRecord::Base
acts_as_ordered_taggable_on :interests
scope :by_join_date, order("created_at DESC")
rolify
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :name, :email, :password, :password_confirmation, :remember_me, :interest_list
# this does not work
before_save :clean_my_tags
# this also does not work
# before_validation :clean_my_tags
def clean_my_tags
if #interest_list
# it appears that at this point, #interest_list is no longer a string, but an
# array of strings corresponding to the tags
#interest_list = #interest_list.map {|x| x.titleize}
end
end
end
Suppose that the last user already has the interest tags: basketball, golf, soccer
If I change the interests like
u = User.last
u.interest_list = "cats, dogs, rabbits"
u.save
Then u.interest_list will be ["cats", "dogs", "rabbits"]
However, u.interests will remain an array of tag objects associated with basketball, golf, soccer
How can I make sure that the tags are formatted before tags are saved?
For some reason your before_save callback needs to come before acts_as_taggable_on in your model, as Dave points out here: https://github.com/mbleigh/acts-as-taggable-on/issues/147
I confirmed this works with rails (3.2) and acts-as-taggable-on (2.3.3):
class User < ActiveRecord::Base
before_save :clean_my_tags
acts_as_ordered_taggable_on :interests
def clean_my_tags
if interest_list
interest_list = interest_list.map {|x| x.titleize}
end
end
end

How to break users into managers and attendees?

First here's my current setup:
models/user.rb
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :confirmable
has_many :events
end
models/event.rb
class Event < ActiveRecord::Base
belongs_to :user
end
So, this works in the sense that a user have many events that s/he can CRUD. Anyone that is not logged in can only view and list all the events.
From this initial setup, I now have another set of users that are attendees and the current users are now actually event managers instead of just a generic user. Essentially, I now have two models that are both users (since they can both log in/sign up and have the same fields) and I was thinking that event should read something like:
models/event.rb
class Event < ActiveRecord::Base
belongs_to :manager
has_many :attendees, :through => :attendance # attendance is a join model
end
but I don't want to create a separate table for managers and attendees and I was thinking of sub classing the user model but I'm not particularly sure about how to go about it. I was looking into the :as and :polymorphic parameters in AR but I'm still not quite sure on how to do it. Help?
What you are looking for is called Single Table Inheritance. Here is one resource on the subject. There are many more. Just google for "Rails Single Table Inheritance".

Rails, Mongoid, Devise User profiles

I'm new to rails (rails 3) and I am learning in practice.
I want to create a User-profile relation. I have created a User model with devise, and that is working well. Then I created a Profile model. The idea is to register an user and the show information about his profile and if the user wants, complete the profile.
But, the profile is related with posts. So, I need to create an empty profile with the register action of the user.
How can I do that?
My idea is to change the UsersController#create method to build the empty profile, but i don't know how.
My models
class User
include Mongoid::Document
devise :database_authenticatable, :registerable, :token_authenticable,
:omniauthable,
:recoverable, :rememberable, :trackable, :validatable
field :username
key :username
embeds_one :profile
attr_accessible :username,:password,:password_confirmation,:remember_me
class Profile
include Mongoid::Document
field :name
field :lastname
...
...
embedded_in :user, :inverse_of => :profiles
referenced_many :posts
Some idea?
It looks like you're only embedding one profile (embeds_one :profile). It should be user.profile, not user.profiles. Also, user.profile will return an instance of that document, not an array of many documents.
You could do something like this in your controller.
user.profile.create(... put any params here ...)
In your view you would then display
<h2>Welcome <%=#user.profile.username %></h2>
You also need to change
embedded_in :user, :inverse_of => :profiles
to
embedded_in :user, :inverse_of => :profile
To see if the user has a profile or not, just see if user.profile returns nil.