I'm trying to implement a top-level account that can have one or more users. My app uses Devise for authentication so I would like to keep the Signup form as part of the User model.
I believe that I've got the models set up correctly, but I am having some trouble figuring out how the registration form should work.
Here's what I've got so far...
User.rb
class User < ActiveRecord::Base
rolify
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable,
:validatable, :omniauthable
# Setup accessible (or protected) attributes for your model
attr_accessible :role_ids, :as => :admin
attr_accessible :name, :email, :password, :password_confirmation, :remember_me, :account, :company
# Association with service accounts
has_many :service_accounts
# Association with company account
belongs_to :account
end
Account.rb
class Account < ActiveRecord::Base
attr_accessible :company
# Association with users
has_many :users, :dependent => :destroy
end
Registrations/new.html.erb
<h2>Sign up</h2>
<%= simple_form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => {:class => 'form-vertical' }) do |f| %>
<%= f.error_notification %>
<%= f.input :name, :autofocus => true, :placeholder => "Name" %>
<%= f.input :email, :placeholder => "Email Address" %>
<%= f.input :password, :placeholder => "Password" %>
<%= f.input :password_confirmation, :placeholder => "Confirm Password" %>
<%= f.button :submit, 'Sign up', :class => 'btn btn-large btn-primary' %>
<% end %>
<%= render "devise/shared/links" %>
Here is what I could use some help with
I want to add a "company" field to the above registration form. Company is a column in the Account table. When a new user registers, I'd like to create a new account for that user and set the company attribute to whatever they provided in the company field.
I'm having trouble with the code needed for both the form (to add the company field) and the controller (to create a new account and update the company field when a user submits the form).
Thanks!
I just finished working on an app with the similar requirements. The relationship looks good. It's likely that you'll want a before_save filter on User that gets the data to be associated with Account and adds/updates the association at the same time.
You should also look into accepts_nested_attributes_for, although I think it's designed to handle the more common situation where the parent (Account, in your case) is driving the creation of children (Users). I suspect you are creating a User with Devise, and either then or later creating the association, and adding associated data to the Account model.
A thing to think about is whether Company is a model of its own, in which case Users have Accounts, and Accounts have Companies. You might want to check out the recent RailsCasts on "multi-tenant" applications -- while they may not apply to your case, they did in mine, and there were a few things I hadn't thought about when managing and structuring my data when I first started the app.
Related
I am building a login system that has two users, buyer and seller, in Rails 4.0.4.
For auth I am using the Devise gem: https://github.com/plataformatec/devise
To create a new buyer I use the route buyer/new. However, the fields for the user do not show in the view. I also using debug to show #buyer.user in the view and it has been created. But when I call f.fields_for #buyer.user do |u| the loop is never entered.
Any ideas of why this is? Also, the polymorphic associations seem to be working in the rails console.
Buyer Controller:
# GET /buyers/new
def new
#buyer = Buyer.new
#buyer.build_user
end
Buyer Model
class Buyer < ActiveRecord::Base
has_one :user, as: :role
accepts_nested_attributes_for :user
end
Buyer/new View
<%= form_for(#buyer) do |f| %>
....
<div class="field">
<%= debug(#buyer.user) %>
<% f.fields_for #buyer.user do |u| %>
<%= u.text_field :email %>
<% end %>
</div>
User Model
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
belongs_to :role, polymorphic: true
Shouldn't you have an = on the fields_for? http://rubydoc.info/docs/rails/ActionView/Helpers/FormHelper:fields_for
E.G.
<%= f.fields_for #buyer.user do |u| %>
I have Account model which have a has_many relationship with User model:
class Account < ActiveRecord::Base
has_many :users, -> { uniq }
accepts_nested_attributes_for :users
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :confirmable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
belongs_to :account
I added avatar attribute to User model using paperclip.
I want each user to have access to the common account settings, and inside it having the possibility to upload his/her own avatar.
I use simple_form so I tried this:
<%= simple_form_for current_account, :html => { :multipart => true } do |f| %>
<%# here come account settings %>
<%= f.input :time_zone, :label => t(".timezone"),
:
:
<%# here I need to access current user attributes %>
<%= f.simple_fields_for :user, current_account.users.first do |user_form| %>
<%= user_form.file_field :avatar, :error => false %>
<% end %>
<% end %>
First problem:
I need some logic to access current_user instead of current_account.users.first. Since there is a superadmin which can access all accounts, use current_user is not enough.
Second (and bigger) problem:
I added in my controller the avatar parameter to the whitelist:
def allowed_params
params.require(:account).permit(:time_zone, :logo, :description, user: [:avatar])
end
When I try to update my model:
if current_account.update(allowed_params)
I get this error:
unknown attribute: user
I also tried:
params.require(:account).permit(:language, :time_zone, :logo, :description, :user_attributes => [:avatar])
and:
params.require(:account).permit(:language, :time_zone, :logo, :description, :users_attributes => [:avatar])
(in plural)
but since I use ActionController::Parameters.action_on_unpermitted_parameters = :raise I get:
found unpermitted parameters: user
It must be something very easy, some help please?
Ok, got it!!
The problem is the one-to-many relationship and the way I tried to access a single instance of user. The correct way to do it is:
<% current_account.users.each_with_index do |user, index|%>
<%= f.simple_fields_for :users, user do |user_form| %>
<%= user_form.file_field :avatar, :error => false %>
<% end %>
<% end %>
As you can see, the iteration should be done over the relation, and only when having a
single instance "in hand" we can user the simple_fields_for.
Also, notice that the first parameter passed to simple_fields_for is :users and not :user, since this is a one-to-many relationship.
I've searched for about an hour now and found an immense amount of questions describing how to add fields to the Devise user model. However I couldn't find any that explain in a clear way how to add one or multiple models to the registration process.
At registration I want the user to fill out an e-mailaddress, password and in addition my client model, company model and address model (so I have all the information the webapplication needs to run properly).
My models are like this
user.rb
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
attr_accessible :email, :password, :password_confirmation, :remember_me, :client
belongs_to :client
end
client.rb
class Client < ActiveRecord::Base
attr_accessible :bankaccount, :email, :logo, :mobile, :phone, :website
has_many :users
has_one :company
has_one :address
accepts_nested_attributes_for :company, :address
end
I think the only way to do this is to create my own RegistrationsController so I can do #client = Client.new and then do this in my view:
<%= f.simple_fields_for #client do |ff| %>
<%= f.simple_fields_for :company do |fff| %>
<% field_set_tag t(:company) do %>
<%= ff.input :name %>
<% end %>
<% end %>
<%= f.simple_fields_for :address do |fff| %>
//address inputs
<% end %>
<% end %>
<fieldset>
<legend><%= t(:other) %></legend>
// other inputs
</fieldset>
<% end %>
The reason I need it to work this way is because I have multiple users who can represent the same client (and thus need access to the same data). My client owns all the data in the application and therefor needs to be created before the application can be used.
Okay, it took me about 8 hours but I finally figured out how to make it work (if someone has a better/cleaner way of doing this, please let me know).
First I've created my own Devise::RegistrationsController to properly build the resource:
class Users::RegistrationsController < Devise::RegistrationsController
def new
resource = build_resource({})
resource.build_client
resource.client.build_company
resource.client.build_address
respond_with resource
end
end
After that I just needed to adjust config/routes.rb to make it work:
devise_for :users, :controllers => { :registrations => "users/registrations" } do
get '/users/sign_up', :to => 'users/registrations#new'
end
Also I had an error in my devise/registrations/new.html.erb. It should have been f.simple_fields_for :client instead of f.simple_fields_for #client.
Now it properly creates all the objects for the nested attributes and automatically saves it when saving the resource.
I'm working on a system where it has 2 models, a user model, a school model.
I'm using devise registration for a regular user sign_up with 'role' as an additional field to indicate whether user is a regular user or a school_user.
For now there is a admin user who creates a new school record while user will register using devise/sign_up action. School doesn't have login information yet.
I can call schools/new action (as school signup link) to add a new school.
Instead I want to extend the devise registration for school which will sign up using 'new school signup link' as a new user (use email, password, role='school' for a user model) and other fields like name, address, etc. going into the regular schools table. This way school admin gets a login account as well.
How do I extend devise/registration form and create these 2 records?
I really appreciate few thoughts.
Override devise registrations route:
routes.rb :
devise_for :users, controllers: {registrations: 'registrations'}
Create controllers/registrations_controller.rb :
class RegistrationsController < Devise::RegistrationsController
after_filter :add_school
protected
def add_school
if resource.persisted? # user is created successfuly
# resource holds all your form data.
resource.schools.build do |school|
school.name = resource.school_name # form fields...
end
#school.save
end
end
end
To validate school fields add validations to your user.rb model
eg:
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 :name,
presence: true,
length: {in: 1..50}
validates :school_name,
presence: true,
length: {in: 1..50}
end
Just for reference:
<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>
<div><%= f.label :school_name %>
<br/>
<%= f.text_field :name, autofocus: true %></div>
<div><%= f.label :email %>
<br/>
<%= f.email_field :email %></div>
# ...
<div><%= f.label :school_name %>
<br/>
<%= f.text_field :school_name %></div>
<div><%= f.submit "Sign up" %></div>
<% end %>
I'm working with Rails 3.1.0 and Devise 1.4.8, and am new to both.
I want to allow multiple users for an account. The first user to sign up creates the account (probably for their company), then that user can add more users. A user is always linked to exactly one account.
I have Users and Accounts tables. Abbreviated models:
class User < ActiveRecord::Base
belongs_to :account
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:confirmable, :lockable, :timeoutable
attr_accessible :email, :password, :password_confirmation, :remember_me
end
class Account < ActiveRecord::Base
has_many :users, :dependent => :destroy
attr_accessible :name, :account_type
end
The question is, when the first user signs up, how do I create both the Account and User?
Do I need to modify/override the Devise registrations_controller,
something like the answer here? I couldn't figure out how to
create the Account then pass it to Devise for creating the User.
account_id is already in the User model. Should I add account_name
and account_type to the User model, and create a new the Account
record if account_id is not passed in? In this case, I'm trying to hide Account creation from Devise, but not sure that will work since I still need to prompt for account_name and account_type on the registration page.
Finally got this to work using nested attributes. As discussed in the comments on Kenton's answer, that example is reversed. If you want multiple users per account, you have to create the Account first, then the User--even if you only create one user to start with. Then you write your own Accounts controller and view, bypassing the Devise view. The Devise functionality for sending confirmation emails etc. still seems to work if you just create a user directly, i.e. that functionality must be part of automagical stuff in the Devise model; it doesn't require using the Devise controller.
Excerpts from the relevant files:
Models in app/models
class Account < ActiveRecord::Base
has_many :users, :inverse_of => :account, :dependent => :destroy
accepts_nested_attributes_for :users
attr_accessible :name, :users_attributes
end
class User < ActiveRecord::Base
belongs_to :account, :inverse_of => :users
validates :account, :presence => true
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:confirmable, :lockable, :timeoutable
attr_accessible :email, :password, :password_confirmation, :remember_me
end
spec/models/account_spec.rb RSpec model test
it "should create account AND user through accepts_nested_attributes_for" do
#AccountWithUser = { :name => "Test Account with User",
:users_attributes => [ { :email => "user#example.com",
:password => "testpass",
:password_confirmation => "testpass" } ] }
au = Account.create!(#AccountWithUser)
au.id.should_not be_nil
au.users[0].id.should_not be_nil
au.users[0].account.should == au
au.users[0].account_id.should == au.id
end
config/routes.rb
resources :accounts, :only => [:index, :new, :create, :destroy]
controllers/accounts_controller.rb
class AccountsController < ApplicationController
def new
#account = Account.new
#account.users.build # build a blank user or the child form won't display
end
def create
#account = Account.new(params[:account])
if #account.save
flash[:success] = "Account created"
redirect_to accounts_path
else
render 'new'
end
end
end
views/accounts/new.html.erb view
<h2>Create Account</h2>
<%= form_for(#account) do |f| %>
<%= render 'shared/error_messages', :object => f.object %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<%= f.fields_for :users do |user_form| %>
<div class="field"><%= user_form.label :email %><br />
<%= user_form.email_field :email %></div>
<div class="field"><%= user_form.label :password %><br />
<%= user_form.password_field :password %></div>
<div class="field"><%= user_form.label :password_confirmation %><br />
<%= user_form.password_field :password_confirmation %></div>
<% end %>
<div class="actions">
<%= f.submit "Create account" %>
</div>
<% end %>
Rails is quite picky about plural vs. singular. Since we say Account has_many Users:
it expects users_attributes (not user_attributes) in the model and tests
it expects an array of hashes for the test, even if there is only one element in the array, hence the [] around the {user attributes}.
it expects #account.users.build in the controller. I was not able to get the f.object.build_users syntax to work directly in the view.
Couldn't you use something like what's covered in these RailsCasts?:
http://railscasts.com/episodes/196-nested-model-form-part-1
http://railscasts.com/episodes/197-nested-model-form-part-2
You could setup your models as described in those screencasts, using accepts_nested_attributes_for.
Then, your views/devise/registrations/new.html.erb form would be for :user like normal, and could include a nested form for :account.
So something like this within that default form:
<%= f.fields_for :account do |account_form| %>
<div>
<p>
<%= account_form.label :name, "Account Name", :class => "label" %>
<%= account_form.text_field :name, :class => "text_field" %>
<span class="description">(e.g., enter your account name here)</span>
</p>
</div>
<div>
<p>
<%= account_form.label :company, "Company Name", :class => "label" %>
<%= account_form.text_field :company, :class => "text_field" %>
</p>
</div>
<% end %>
This is sample code from an app I'm working on and I'm using the simple_form gem, so the helpers used in your app may be different, but you'll probably get the idea.
So when a user is created (when they register), they can also fill in the info that'll be used by the Account model to create their account once they hit the "Sign Up" button.
And you may want to set an attribute on that user like "admin" too...sounds like this initial user will be the "admin" user for the company, though other users may have access too.
Hope that helps.
The best solution would be to use a gem.
Easy way: milia gem
Subdomain way: apartment gem