Help simplifying code by removing some if's

I need some help simplifying some code. Some ago, I was trying to
validate a User model depending on the action they were performing.
http://www.ruby-forum.com/topic/2189458#new

For example:

  1. Signing up (validate presence of username)
  2. Inviting someone to user the app (DO NOT validate presence of
    username
    because invited user is supposed to pick his username)
  3. Accepting invitation link (validate presence of username)

So Frederick C. (thanks Frederick) suggested I validate depending on
the user state. So I create a user_state attribute for the User model.


The following is for ACCEPTING INVITATION LINK. An admin invites an
user. The user is created with user_state=“invited”. The invited user
receives an email with a link. The link takes him to a form to pick his
username and password.

This is the code I came up with. It works, but I have a lot of if’s
statements and I know there should be a cleaner way to do it.

Can anyone give me any suggestions as to how to simplify it? I’m a
newbie, please understand hehe, thanks :slight_smile:

user.rb

validates :username,
:presence => true,
:uniqueness => true,
:if => :are_you_activating_your_account?,
:on => :update

def are_you_activating_your_account?
if self.user_state==“invited”
true
else
false
end
end


users_controller.rb

def activate
@user = User.find(params[:id])

respond_to do |format|

it sets up the username and password, applying validation

if @user.update_attributes(params[:user])
# if passed validation,
# set user state to confirmed
@user.user_state = “confirmed”
@user.confirmed_at = Time.now
if @user.update_attributes(params[:user])
# send confirmation email
Notifier.user_confirmed(@user).deliver
flash[:notice] = "You’re all set, " + @user.first_name + “!”
format.html { redirect_to(:action => ‘complete’)}
else
flash[:error] = ‘Failed to set user state to confirmed.’
format.html { render :action => “invitation” }
end
else
flash[:error] = ‘User was not updated.’
format.html { render :action => “invitation” }
end
end
end

On Aug 3, 2011, at 1:30 PM, Leonel . wrote:

username and password.
:presence => true,
end
I’ll leave the rest for others more experienced, but this leaped out
at me. The previous can be written as this:

def are_you_activating_your_account?
self.user_state == ‘invited’
end

Walter

Thanks, it did simplify it. Any suggestions on the controller?

Leonel . wrote in post #1014810:

Thanks, it did simplify it. Any suggestions on the controller?

if @user.update_attributes(params[:user])
# if passed validation,
# set user state to confirmed
@user.user_state = “confirmed”
@user.confirmed_at = Time.now
if @user.update_attributes(params[:user])

Can that last if statement ever be false?