As a first step you could use the same variable regardless of the profile type i.e.
@profile = @user.isAdmin? ? AdminProfile.new : PersonalProfile.new
This is using Ruby's conditional operator which has the form condition ? value if true : value if false. i.e. if @user.isAdmin?
evaluates to true
then @profile
gets the value after the ?
. If @user.isAdmin?
is false then @profile
gets the value after the :
. Notice that because your method name already ends in a ?
you get this appearance of a double ?
.
and then
if (@user.isAdmin?)
@user.admin_profile = @profile
@user.admin_profile_id = @profile.id
else
@user.personal_profile = @profile
@user.personal_profile_id = @profile.id
end
Also, not sure if this is Rails code, but if it is then you don't need to set admin_profile
and admin_profile_id
, and in fact @profile.id
won't be set yet as the profile hasn't saved. So possibly you could reduce the if/else
to:
if (@user.isAdmin?)
@user.admin_profile = @profile
else
@user.personal_profile = @profile
end
Update
You should also look into the create_association method which you get when you use a belongs_to
association. You can have Rails create and save an associated object all in a single step e.g.
@user.create_personal_profile