0

This should be a fairly simple error to fix (I hope). When a joke on my app is approved, I want that user to be awarded 5 manpoints (don't ask). I currently have this in my 'jokes_controller`:

  def approve
    @joke = Joke.find(params[:id])
    @joke.update_attributes(approved: true)
    if @joke.user.manpoints = nil
      @joke.user.manpoints = 5
    else
      @joke.user.manpoints += 5
    end
    @joke.save
    redirect_to jokes_path
  end

I'm getting this error when I try to approve a joke:

undefined method `+' for nil:NilClass

I thought += was the "Ruby way" to do this? Can anyone set me straight?

1
  • try changing @joke.user.manpoints = nil to @joke.user.manpoints.nil? and @joke.user.manpoints == nil should be the correct syntax Commented Aug 14, 2016 at 0:14

1 Answer 1

0

Change = in if condition to ==. I assume you need to compare manpoints with nil, not to assign nil to manpoints. It should be like:

if @joke.user.manpoints == nil
  ...

You can omit == operator here:

unless @joke.user.manpoints
  ...

PS. Why are you excepting that manpoints will be nil?

Sign up to request clarification or add additional context in comments.

4 Comments

Those changes get rid of the error, but the user's manpoints are still nil after the approve action.
You need to save the user instance. Save it with @joke.user.save.
Perfect! Thank you!
You're welcome :) btw, you can avoid the comparison. Use default value with migration. related info

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.