简体   繁体   中英

Rails Devise registration with an additional model

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM