Rails Registration Development with an Additional Model

I searched for about an hour and found a huge number of questions describing how to add fields to the Devise user model. However, I could not find anything explaining in a clear way how to add one or more models to the registration process.

When registering, I want the user to fill in the email address, password, and, in addition, my client model, company model, and address model (so I have all the information that the web application needs to run properly).

My models are like

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 that I can do @client = Client.new and then do it in my opinion:

  <%= 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 this is because I have several users who can represent the same client (and therefore need access to the same data). My client owns all the data in the application and therefore must be created before the application will be used.

+7
source share
1 answer

Ok, it took me about 8 hours, but I finally figured out how to get it working (if anyone has a better / cleaner way to do this, please let me know).

First, I 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 configure config / routes.rb for it to 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 project / registration / new.html.erb. This should be f.simple_fields_for :client instead of f.simple_fields_for @client .

Now it correctly creates all objects for nested attributes and automatically saves them when saving a resource.

+6
source

All Articles