Question

I'm trying to make it so that when a new User is created (through Devise), a new Household(essentially a group) model will be created if no previous Household model with that name exists.

pseudocode:

if Household.find(params[:household_name))
  # allow current_user to join household
else
 # create new Household model with User's household_name parameter
end

I've overwritten the base user controller from Devise::RegistrationsController with controllers/registerhousehold_controller.rb:

class RegisterhouseholdController < Devise::RegistrationsController

But I'm not sure how to implement the actual creation here. Any suggestions?

Was it helpful?

Solution

No changes in controller required as far as I see.

User.rb

after_create :create_or_join_to_household

def create_or_join_to_household
 household = Household.find(params[:household_name])
 if household.present?
   self.join_to_household
 else
   Household.create(name: params[:household_name])
   #or self.households.create(name: params[:household_name])
   #if you have a household - user relation somehow
end

p.s.

join_to_household would be another method in your user model that will create a household_users relation.

OTHER TIPS

Simple - use the before_create callback in the user model to build the object, then you'll be able to use it when you save:

#app/models/user.rb
Class User < ActiveRecord::Base
    before_create :set_household, if: Proc.new {|user| user.household_id.present? }

    private

    def set_household
        if house = Household.find(self.household_id)
           #if it is set
        else
           #create a new houshold
        end
    end
end

I had to call custom method after successful sign up, on my previous task. U also need something similar.

I'm not sure about overriding.

Try this in App. controller

class ApplicationController < ActionController::Base

def after_sign_in_path_for(resource)
 if Household.find(params[:household_name))
    # allow current_user to join household
 else
    #create new Household model with User's household_name parameter
 end
 root_path
end

end

Check this

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top