user266003
user266003

Reputation:

Unable to write variable to session in Ruby on Rails

Here is some code I'm using just to avoid of hardcoding session variables.

#application_controller
  def redirect_to_new_order?
    session[:redirect_to_new_order]
  end

  def redirect_to_new_order=(value)
    session[:redirect_to_new_order] = value
  end

#another_controller
#.............
def some_action
   redirect_to_new_order = true
   #viewed by debugger
   # redirect_to_new_order? is equal to nil 
   # session[:redirect_to_new_order] is equal to nil as well
end

As you can see, redirect_to_new_order? and session[:redirect_to_new_order] are nil for some reason.

Why is this happening?

UPDATE: Here is a code similar to given above. But it does call a method and doesn't create a local variable. Why?

class SomeClass

    def initialize
        @some_var = "999"
    end
    def var1
        @some_var
    end

    def var1=(value)
        @some_var=value
    end

    def method1
      var1 = 111
      puts var1
      puts @some_var  
    end
end

a = SomeClass.new
a.method1 # prints 111 and 999 but why?

Upvotes: 2

Views: 304

Answers (2)

Mischa
Mischa

Reputation: 43298

Because it's unclear if you want to set a local variable or call the setter method. Ruby chooses to set a local variable in that case. See these two answers:

Upvotes: 0

austen
austen

Reputation: 3314

The reason is you are not invoking the redirect_to_new_order= method. Rather you are setting a local variable redirect_to_new_order with a value of true. As a sanity check, add a raise "BOOM" line to the assignment method and you'll see that the method isn't invoked.

You need an explicit receiver or else you are setting a local variable in your controller.

self.redirect_to_new_order = true

will do the trick.

Upvotes: 2

Related Questions