I want to override Devise’s RegistrationsContollers‘ create action so that when a user signs up, I can associate a UserProfile model with that user.
So, following the guidelines in the Devise Readme, I override 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 is creating a record in the users table, but how do I associate a UserProfile with that record?
I’ve tried googling but I simply can’t get this to work! Any help is much appreciated.
(I’m now using Devise 1.1.5 on Rails 3.0.3)
SOLVED:
Adding solution for benefit of 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
selfrefers to the contoller not the model in this context.Also, does the user model have many UserProfiles? Otherwise if they don’t (ie they only have one), then you should use
@user.build_user_profile, not@user.user_profiles.buildI’d also recommend doing this at the model level, not the controller level, using a callback such as
before_createorafter_create, ie: