A
A
anasasiakiri4enko2016-07-24 22:57:51
Ruby on Rails
anasasiakiri4enko, 2016-07-24 22:57:51

How to create a User with a profile?

Good evening!
After registration, I need the user to have his own profile, which is tied specifically to this user who is registered. I explain: the user has registered, and immediately there is an opportunity to change the user's data (or add new data, instead of stubs). I use the devise gem, and, in this case, I do not mean adding fields to the database when registering, but editing the profile that will be linked to my account.
It turns out that each registered user can edit either the same profile or the same profiles (if resources (Without s) ).
The user model owns a profile (has_one :profile and there was an attempt with has_many:profiles). Models Profile (belongs_to :user)
I have trouble with these associations (, put me on the right path! How to solve this problem? How would you decide?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Amelchenko, 2016-07-25
@anasasiakiri4enko

1. Add a devise controller to the application ( rails generate devise:controllers users ), edit config/routes.rb to use a custom controller

devise_for :users,
             controllers: { registrations: "users/registrations" }

2 In the create method of the controller, add resource.create_profile
class Users::RegistrationsController < Devise::RegistrationsController
  def create
    super
    if resource.save
        resource.create_profile
    end
  end

models/user.rb
has_one :profile, dependent: :destroy

A
Andrey Demidenko, 2016-07-25
@Dem1

For example, you can redirect after registering to the ProfilesController controller in a new action.
Also, if you want to force the user to complete fields, create a before_action :require_profile! and redirect the user until they complete the profile. Just don't forget to remove new and create from before_action for ProfilesController

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question