Initialize a session var as array in Rails 3
I need to initialize a session var as array. Where i do that?
when i try to do this:
session[:complains_id] << params[:id]
i get this message
You have a nil object when you didn't expect it开发者_运维技巧! You might have expected an instance of Array. The error occurred while evaluating nil.<<
I know that i have to initialize the var but i dont know where.
Thanks!
Just do:
(session[:complains_id] ||= []) << params[:id]
Which is saying:
if
session[:complains_id]
returns nil, set it to [].Append
params[:id]
tosession[:complains_id]
Demo:
ruby-1.9.2-p136 :007 > (session[:complains_id] ||= []) << 5
=> [5]
ruby-1.9.2-p136 :008 > (session[:complains_id] ||= []) << 3
=> [5, 3]
ruby-1.9.2-p136 :009 > (session[:complains_id] ||= []) << 1
=> [5, 3, 1]
精彩评论