无解。。颠覆了我的世界观。
大家可以在 console 里面试试。
使用的 ruby 版本是 1.8.7 Rails 2.3.17
a = {"array_item_0" => [{"attr_0" => 0}, {"attr_1" => 1}], "array_item_1" => [{"attr_2" => 2}, {"attr_3" => 3}]}
Rails.cache.write "test_a", a, :expires_in => 1.hours; nil
b = (Rails.cache.read "test_a").dup;nil
merge_test = [{"additional_attr_0" => 0}, {"additional_attr_1" => 1}]
b["array_item_0"].each_with_index {|item, index| item.merge! merge_test[index]}
Rails.cache.read "test_a"
>> {"array_item_1"=>[{"attr_2"=>2}, {"attr_3"=>3}], "array_item_0"=>[{"additional_attr_0"=>0, "attr_0"=>0}, {"additional_attr_1"=>1, "attr_1"=>1}]}
不用 merge! 试试呢?还是变化了
a = {"array_item_0" => [{"attr_0" => 0}, {"attr_1" => 1}], "array_item_1" => [{"attr_2" => 2}, {"attr_3" => 3}]}
Rails.cache.write "test_a", a, :expires_in => 1.hours; nil
b = (Rails.cache.read "test_a").dup;nil
merge_test = [{"additional_attr_0" => 0}, {"additional_attr_1" => 1}]
b["array_item_0"].each_with_index {|item, index| b["array_item_0"][index] = item.merge merge_test[index]}
Rails.cache.read "test_a"
>> {"array_item_1"=>[{"attr_2"=>2}, {"attr_3"=>3}], "array_item_0"=>[{"additional_attr_0"=>0, "attr_0"=>0}, {"additional_attr_1"=>1, "attr_1"=>1}]}
难道只有用这种方式 才能保证 cache 不会变?
a = {"array_item_0" => [{"attr_0" => 0}, {"attr_1" => 1}], "array_item_1" => [{"attr_2" => 2}, {"attr_3" => 3}]}
Rails.cache.write "test_a", a, :expires_in => 1.hours; nil
b = (Rails.cache.read "test_a").dup;nil
merge_test = [{"additional_attr_0" => 0}, {"additional_attr_1" => 1}]
c = {}
c["array_item_0"] ||= []
b["array_item_0"].each_with_index {|item, index| c["array_item_0"] << (item.merge merge_test[index])}
Rails.cache.read "test_a"
>> {"array_item_0"=>[{"additional_attr_0"=>0, "attr_0"=>0}, {"additional_attr_1"=>1, "attr_1"=>1}]}