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:
- Signing up (validate presence of username)
- Inviting someone to user the app (DO NOT validate presence of
username
because invited user is supposed to pick his username) - 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
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