def create
logout_keeping_session!
success = false
@user = User.new(params[:user])
@user.self_register = true
@company = Company.new(params[:company])
@user.current_company = @company
@company.time_zone = @user.time_zone
success = @company.save if @user.valid_with_captcha?
success = ( @user && @user.save ) if success
if success && @user.errors.empty?
@company.email = @user.email
@company.save
@role = Role.new({:role => Role::Roles::ADMIN_ROLE, :company_id => @company.id,
:user_id => @user.id})
@role.save
@user.status = User::Status::NORMAL
#create testing initial data
@company.create_initial_data
redirect_back_or_default('/')
flash[:notice] = t('users.flash.signing_up_success')
else
#flash[:error] = t('users.flash.signing_up_fail')
render :action => 'new', :layout => "registration"
end
end
Refactorings
No refactoring yet !
David Calavera
May 4, 2009, May 04, 2009 15:35, permalink
I'd split that method in several methods into the user model, like that, more or less
class User < ActiveRecord::Base
def self.register(params)
User.new(params[:user].merge({:self_register => true}))
end
def create_company(params)
self.current_company = Company.new(params[:company].merge({:time_zone => self.time_zone}))
self.current_company
end
def perform_save
success = if valid_with_captcha?
@current_company.save && self.save
end
end
def create_role(role = Role::Roles::ADMIN_ROLE, status = User::Status::NORMAL)
self.role = Role.create(:role => role, :company_id => @current_company.id, :user_id => @id)
self.status = status
self.role
end
end
def UserController < ApplicationController
def create
@user = User.register(params)
@company = @user.create_company(params)
if @user.perform_save && @user.errors.empty?
@company.email = @user.email
@company.save
@role = @user.create_role
@company.create_initial_data
redirect_back_or_default('/')
flash[:notice] = t('users.flash.signing_up_success')
else
render :action => 'new', :layout => "registration"
end
end
end
danielharan
May 4, 2009, May 04, 2009 21:35, permalink
Check out giraffesoft's active_presenter on github; it should be helpful here
Adam
May 5, 2009, May 05, 2009 17:25, permalink
Your model seems screwy. For example, the user is associated to the company twice. Why?
Because I am having trouble understanding what you are trying to achive I am unable to provide a full solution, however I will give you this. The accepts_nested_attributes_for and delegate methods look like they will be of interest to you.
class User < ActiveRecord::Base
has_one :role
has_one :company
accepts_nested_attributes_for :role, :current_company
end
class Company < ActiveRecord::Base
belongs_to :user
delegate :email, :time_zone, :to => :user
end
class Role < ActiveRecord::Base
belongs_to :user
end
class UsersController < ApplicationController
def create
@user = User.create(params[:user])
end
end
I need create user, company and role. Help me