开发者

Where can I use cookies in Ruby on Rails

I'm using controller's initializer to setup stuff that I will need.

def initialize
  super()
  a = coo开发者_StackOverflow中文版kies[:a] # EXCEPTION

end

However I can't use cookies because it's null, the system hasn't read them from the header yet.

The same problem was with ASP.NET MVC, where I couldn't access the cookies in the constructor, but I could access them in the Initialize() method.

How can I get the cookies in Rails?


If you want to set something up prior to each request you should use a before_filter.

class MyController << ApplicationController
  before_filter :cookie_setup

  def cookie_setup
    a = cookies[:a]
    .. whatever you want to do with 'a'
  end
end


Former I have problems with this too, this should works:

cookies['a'] = 'value'
a = cookies['a']


Specifically, cookies is a hash and what you are doing is adding a key value pair with the syntax hash[:key] = value to the hash. So adding a key, without assigning a value, will give you a nil value when you ask for it.

irb(main):006:0> cookies = {}
=> {}
irb(main):007:0> cookies[:a] = 'value'
=> "value"
irb(main):008:0> cookies.inspect
=> "{:a=>\"value\"}"
irb(main):010:0> a= cookies[:b]
=> nil
irb(main):011:0> cookies.inspect
=> "{:a=>\"value\"}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜