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?

Liz
  • 1,369
  • 2
  • 26
  • 61
  • try changing `@joke.user.manpoints = nil` to `@joke.user.manpoints.nil?` and `@joke.user.manpoints == nil` should be the correct syntax – mrvncaragay Aug 14 '16 at 00:14

1 Answers1

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?

user1201917
  • 1,360
  • 1
  • 14
  • 27
  • Those changes get rid of the error, but the `user`'s `manpoints` are still `nil` after the approve action. – Liz Aug 14 '16 at 00:20
  • You need to save the `user` instance. Save it with `@joke.user.save`. – user1201917 Aug 14 '16 at 00:32
  • Perfect! Thank you! – Liz Aug 14 '16 at 00:39
  • You're welcome :) btw, you can avoid the comparison. Use default value with migration. [related info](http://stackoverflow.com/questions/6167994/assigning-default-value-while-creating-migration-file) – user1201917 Aug 14 '16 at 00:47