简体   繁体   中英

Rails session values between symbols and strings

A controller processes temporary values for partial_budget:

partial_budget = { shop_id: params[:pushbudget][:shop_id].to_i, budget: budget }
@this_budget_item = session[:pushbudget].detect {|i| i[:shop_id] == params[:pushbudget][:shop_id].to_i }
if @this_budget_item.nil?
  session[:pushbudget]  << partial_budget
else
  session[:pushbudget].delete(@this_budget_item)
  session[:pushbudget]  << partial_budget
end

On one run the inserted item is the last in the array has keys that are symbols, not strings,

{"shop_id"=>110, "budget"=>"333"}
{"shop_id"=>111, "budget"=>"344"}
{:shop_id=>141, :budget=>"009"}

On the next run, an edited item is again the last in the array with keys as symbols, not strings. But the previous item is now a string.

{"shop_id"=>111, "budget"=>"344"}
{"shop_id"=>141, "budget"=>"009"}
{:shop_id=>110, :budget=>"333"}

So rails is mixing things up as the process goes along, leading to the failure of

values = session[:pushbudget].map {|i| i[:budget].to_i }
values.sum

How can the data be consistently stored and thus retrieved for processing?

Due to the way session is stored, it's serialized as JSON, the keys will typically be "stringified" as JSON does not understand symbols.

You'll either have to account for this and just use string keys, or use a wrapper like HashWithIndifferentAccess to hide the differences.

Note: Using session for storing non-trivial datastructures is not recommended. While technically permitted it does not come without costs. The default storage method for session is a cookie, so the more data you pile in, the bigger the cookie gets, and remember the cookie is transmitted for each and every request, increasing overhead.

Tip: If you're working with temporary data that's more than a handful of values you may want to use sessionStorage or localStorage instead. This is near zero cost and doesn't need to be transmitted as part of each request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM