0

I have a Rails 4 app that uses Devise.

I'm trying to let the User model alone so that I don't cross paths with Devise, so I created a Profile model for all my settings/views the user will have.

The Profile has

belongs_to :user

The User has

has_one :profile

Where do I put the logic that the app needs to know to create a profile upon new user creation, and delete it upon user deletion?

Chris Valentine
  • 1,557
  • 1
  • 19
  • 36
  • I would go with an after_create callback as pointed out below, but there's really no reason to be afraid of [customizing your User model](http://jacopretorius.net/2014/03/adding-custom-fields-to-your-devise-user-model-in-rails-4.html). It's not that tough, and it's likely to save you trouble down the line. – MarsAtomic Jun 18 '15 at 20:35
  • would you know how to add in the user controller/views etc. if devise is already installed without messing up devise? – Chris Valentine Jun 18 '15 at 22:42
  • The controllers and views for User have little to do with Devise. Devise has a registrations_controller.rb file, and a new user is created when a new Devise registration is created. You'd also be modifying app/views/devise/registrations/new.html.erb and so on. These modifications are beyond the scope of a comment, so please read the Devise doc, make some effort to try coding what you can and post follow up questions separately. – MarsAtomic Jun 18 '15 at 23:28

2 Answers2

2

You can use Active Record Callbacks to create a profile. And you can use dependent: :destroy to make sure the profile will get destroyed when the user is destroyed.

In your models/user.rb

class User < ActiveRecord::Base
  has_one :profile, dependent: :destroy # destroy user's profile

  after_create :create_default_profile

  ... ...

  private
    def create_default_profile
      Profile.create(user_id: self.id)
    end
end 
Steven Yue
  • 966
  • 1
  • 8
  • 16
1

Rails associations have a dependent option, which handles deleting associated records.

User < ActiveRecord::Base
  has_one :profile, dependant: :destroy
end
  • :destroy, when the object is destroyed, destroy will be called on its associated objects.
  • :delete, when the object is destroyed, all its associated objects will be deleted directly from the database without calling their destroy method.

Creating the associated Profile can be done with ActiveRecord callbacks or in the controller. I have getting more and more weary of callbacks since its difficult to control when and where they are actually run.

In the case of Devise you would override the Devise::RegistrationsController.

Community
  • 1
  • 1
max
  • 96,212
  • 14
  • 104
  • 165
  • However, I would not add a bunch of complication just do avoid clashing with Devise. Devise does not add a huge amount of properties even with a bunch of modules activated. I would consider adding a `Users::Preference` model or something like it if you want to have a bunch of user prefs in your app. – max Jun 18 '15 at 20:37