Dominik
Dominik

Reputation: 203

Why variable return nil

I've got little problem. I've got two method, index and create. When I try to check what's in randomUserId I see 'nill', but in View everything is correct.

  def index
    @randomUserId = rand(1..30)
  end

  def create
    puts "RANDOM: "
    puts @randomUserId

  end

Upvotes: 0

Views: 91

Answers (2)

Taryn East
Taryn East

Reputation: 27747

create and index are two very different methods. In a Controller they are not called together. You call only one or another. According to the code that you have supplied, you are only setting the value of @randomUserId in the index action.... not in the create action. You can't call a variable used in a different action - the value you set it to no longer exists, and will (correctly) return nil.

If you want the value of @randomUserId in the create action, you have to set it again in the create action, or pass it through the params somehow.

If the former, just copy the line that says @randomUserId =rand(1..30).

If the latter, then you will need to tell us a lot more about what you are trying to do, your views etc, before we can help you.

Upvotes: 0

steenslag
steenslag

Reputation: 80105

puts returns nil after it outputs a string, so the create methods returns nil.

Upvotes: 1

Related Questions