Reputation:
I've created a Ruby on Rails application in which users can login and logout, and new accounts can be created. Users have an integer "rankid", and depending their rankid have different permissions on the site.
I want users to be able to upgrade to the next rank by going to ROOTURL/upgrade
- so in my routes.rb I have the following:
map.connect '/upgrade', :controller => 'users', :action => 'upgrade'
Which makes use of the following method in my users controller:
def upgrade
@CurrentID = session[:user_id]
@user = User.find(@CurrentID)
if @user.rankid = 0
@user.rankid = 1
redirect_to root_url, :notice => "Upgraded to VIP!"
return
end
if @user.rankid = 1
@user.rankid = 2
redirect_to root_url, :notice => "Upgraded to Admin!"
return
end
end
I setup the authentication using this tutorial and can't figure out why it wont work. Sorry if this is a really stupid mistake - I'm very new to both Ruby and Rails.
Upvotes: 1
Views: 126
Reputation: 124429
First, your if
statements need a double equals sign, which will compare @user.rankid
to 0
instead of setting it to 0
.
if @user.rankid == 0
Next, you're never saving your users after updating them. Lastly, use an elsif
on your second block. Otherwise, a user will be upgraded to VIP and then immediately upgraded to admin. By using an else/elsif, you don't need to hard code a return statement.
Full code:
def upgrade
@user = User.find(session[:user_id])
if @user.rankid == 0
@user.update_attributes(:rankid => 1)
redirect_to root_url, :notice => "Upgraded to VIP!")
elsif @user.rankid == 1
@user.update_attributes(:rankid => 2)
redirect_to root_url, :notice => "Upgraded to Admin!"
end
end
Upvotes: 1
Reputation: 493
Are you setting session[:user_id] before your user hits the Users#upgrade action i.e. login?
You can also skip the extra variable and just use
@user = User.find(session[:user_id])
But before you go and use the result make sure you actually get something useful back
if @user
@user.rankid += 1;
@user.save # Maybe even error check this
case @user.rankid
when 1
notice = "Upgraded to VIP!"
when 2
notice = "Upgraded to Admin!"
else
notice = "r00t!"
end
redirect_to root_url, :notice => notice
return
else
# some problem with your user or missing session[:user_id]
end
Upvotes: 0