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