Reputation: 1528
I'm developing a small application in Ruby-On-Rails. In a controller I have this piece of code:
@user = User.find(current_user.id)
@user.number = current_user.number + 1
@user.save!
Although it locally runs without problems, it crashes on Heroku at line two, with the following error:
NoMethodError (undefined method `+' for nil:NilClass)
Any tips on how to solve the problem?
Upvotes: 0
Views: 114
Reputation: 4796
You can do this too:
@user.number = current_user ? current_user.to_i : 0
@user.save!
Upvotes: 1
Reputation: 3669
If you are storing the number as attribute in your database you should set the default state to 0.
create new migration and regenerate the number column.
def change
remove_colum :users, :number
add_column users, :number, :integer, :default => 0
#ensure that all users with number == nil have got 0 instead nil
User.where(:number => nil).update_all(:number => 0)
end
Upvotes: 3