How to add a UserProfile to a User when user signs up? (Devise, Rails 3)
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 Use开发者_开发问答rs::RegistrationsController < Devise::RegistrationsController
def create
super
@user.build_user_profile
@user.user_profile.some_data = 'abcd'
@user.save!
end
end
self
refers 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.build
I'd also recommend doing this at the model level, not the controller level, using a callback such as before_create
or after_create
, ie:
class User < AR
has_one :user_profile
after_create :build_profile
def build_profile
self.build_user_profile
...
end
end
精彩评论