Search code examples
ruby-on-railsdeviseregistrationprofilecreation

Create a user profile upon registration add profile form fields to devise registrations#new form


I have a rails 3.1 app with devise:

  • User has_one profile
  • Profile belongs_to user
  • Overruled the devise registration_controller
  • Custom registration views all working fine, registration works fine

Now I could like to add this:

  • On the registration page I want to add fields from the profile, like first name, lastname
  • There is no user yet, that is going to be created when submitting the form
  • I need the profile to be created with this first name,last

How would I do this? I tried several ideas, also from stack overflow but cannot seem to get it working. I tried nested attributes wich is not working the way to do this would to create a profile record in the db at the moment the user registers wich inserts the first name and last name

My registrations#new view:

= simple_form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f|

    = devise_error_messages!

    = f.input :username,                  :label => 'Username'
    = f.input :email,                     :label => 'Email'
    = f.input :password,                  :label => 'Password'
    = f.input :password_confirmation,     :label => 'Password confirm'

    // start fields for profile
    = f.fields_for :profile do |f|
      = f.label :bod_day
      = f.text_field :bod_day
    // end fields for profile


    = f.button :submit, t(:submit, :scope => :register)

In my user model i have this:

  accepts_nested_attributes_for :profile

Solution

  • I think the problem is that no profile exists on that user when the form is rendered, a simple way to get round this might be to build it in memory before rendering the fields like so:

    = simple_form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f|
    
        = devise_error_messages!
    
        = f.input :username,                  :label => 'Username'
        = f.input :email,                     :label => 'Email'
        = f.input :password,                  :label => 'Password'
        = f.input :password_confirmation,     :label => 'Password confirm'
    
        // make a new profile in memory
        = resource.build_profile
    
        // start fields for profile
        = f.fields_for :profile do |f|
          = f.label :bod_day
          = f.text_field :bod_day
        // end fields for profile
    
    
        = f.button :submit, t(:submit, :scope => :register)