How to add UserProfile to a user during user registration? (Development, rails 3)

I want to override Devise RegistrationsContollers'create an action so that when a user subscribes, I can associate a model UserProfilewith that user.

So, following the recommendations in the Readme, I redefine the action:

#File app/controllers/registrations_controller.rb:    
class Users::RegistrationsController < Devise::RegistrationsController
  def create
    # some code here..
    self.user_profiles.build #Error (no method `user_profiles`)
    current_user.user_profiles.build #Error (current_user is nil)
    some other way???
  end
end

#File routes.rb:
devise_for :users, :controllers => { :registrations => 'users/registrations' }

Devise creates an entry in a table users, but how do I link UserProfileto this entry?

I tried google search but i just can't get it to work! Any help is greatly appreciated.

(I am now using Devise 1.1.5 on Rails 3.0.3)

SOLVE:

Adding a solution for others:

#File app/controllers/registrations_controller.rb:    
class Users::RegistrationsController < Devise::RegistrationsController
  def create
    super
    @user.build_user_profile
    @user.user_profile.some_data = 'abcd'
    @user.save!
  end
end
+3
source share
1 answer

self refers to the contoller, not the model in this context.

, UserProfiles? , (.. ), @user.build_user_profile, @user.user_profiles.build

, , , before_create after_create, :

class User < AR
    has_one :user_profile

    after_create :build_profile 

    def build_profile
        self.build_user_profile
        ...
    end
end
+3

Source: https://habr.com/ru/post/1777419/


All Articles