-1

当我在复制到某个变量后对列值执行一些逻辑时,对象上的实际列值正在发生变化,我的模型方法是,

  def copy_configuration_values
    element_positions_dup = element_positions.dup
    cert_element.read_attribute(:field_names)["configuration_values"].each { |k, v|
      element_positions_dup["configuration_values"][k] = v if configuration_value_present?(k)
    }
    element_positions_dup
  end

  def configuration_value_present?(configuration)
    element_positions["configuration_values"] && element_positions["configuration_values"][configuration]
  end

当我从控制台调用此方法时,如下所示,

1.9.3p194 :001 > t = CertTemplate.find 30
CertTemplate Load (0.3ms)  SELECT `cert_templates`.* FROM `cert_templates` WHERE `cert_templates`.`id` = 30 LIMIT 1
=> #<CertTemplate id: 30, name: "aaaaaaaaaaaq", cert_element_id: 22, element_positions: {"configuration_values"=>{"Program"=>"9.523810492621529,24.627720154437824"}, "custom_fields"=>{"college"=>"22.64550296843998,15.349369638973906", "code"=>"16.790123349144345,15.463920671915272"}, "custom_fields_for_rows"=>{"subject name"=>"30.68783230251736,16.609393247624034"}}, created_at: "2012-08-08 07:18:33", updated_at: "2012-08-16 08:03:52", image_file_name: "Marksheet_Updated.jpg", image_content_type: "image/jpeg", image_file_size: 2236497, image_updated_at: "2012-08-08 07:18:33"> 
1.9.3p194 :002 >
1.9.3p194 :003 >   t.copy_configuration_values
CertElement Load (0.2ms)  SELECT `cert_elements`.* FROM `cert_elements` WHERE `cert_elements`.`id` = 22 LIMIT 1
=> {"configuration_values"=>{"Program"=>"2"}, "custom_fields"=>{"college"=>"22.64550296843998,15.349369638973906", "code"=>"16.790123349144345,15.463920671915272"}, "custom_fields_for_rows"=>{"subject name"=>"30.68783230251736,16.609393247624034"}} 
1.9.3p194 :004 > 
1.9.3p194 :005 >   t
=> #<CertTemplate id: 30, name: "aaaaaaaaaaaq", cert_element_id: 22, element_positions: {"configuration_values"=>{"Program"=>"2"}, "custom_fields"=>{"college"=>"22.64550296843998,15.349369638973906", "code"=>"16.790123349144345,15.463920671915272"}, "custom_fields_for_rows"=>{"subject name"=>"30.68783230251736,16.609393247624034"}}, created_at: "2012-08-08 07:18:33", updated_at: "2012-08-16 08:03:52", image_file_name: "Marksheet_Updated.jpg", image_content_type: "image/jpeg", image_file_size: 2236497, image_updated_at: "2012-08-08 07:18:33"> 
1.9.3p194 :006 >

我的实际列值正在改变,我做错了什么。提前谢谢。

4

1 回答 1

1

看起来问题是当您遍历键值而不是副本时,您正在分配对嵌套哈希的引用。

具体而言,两者中的“custom_fields”键都将指向element_positionselement_positions_dup值相同的 Hash 对象,因为您分配它而不复制它。要修复它,请尝试

...
element_positions_dup["configuration_values"][k] = v.dup if configuration_value_present?(k)
...

编辑:是的,你需要深拷贝

使用 Marshal 序列化

于 2012-09-10T10:03:11.320 回答