簡體   English   中英

Ruby更新哈希數組中的所有相同對象數據以獲取JSON.parse

[英]Ruby update all same object data in hash array for JSON.parse

所以a = first

=> <Ng::EntityConfiguration id: 15903, entity_id: 1, entity_type: "Ng::Company", key: "wpa2.psk", value: "[{"ssid":"Main-Hall-Staff","password":"abc123","dhcp":"Enabled"},{"ssid":"Main-Hall-Guest","password":"def456","dhcp":"Disabled"}]", created_at: "2016-11-08 11:03:51", updated_at: "2016-11-08 11:03:51", name: "WIFI/Main Hall">

我有a.value這將返回:

"[
  {\"ssid\":\"Main-Hall-Staff\",\"password\":\"abc123\"},
  {\"ssid\":\"Main-Hall-Guest\",\"password\":\"def456\"}
]"

我的問題是,如何同時更新和保存密碼值?

new_pass1 = 'xyz123'
new_pass2 = 'xyz321'

我已經嘗試了下面的代碼,但是如果我只有一個hash_array,這只會更新第一個密碼。

這是我的完整代碼

def encrypt_pass
  # get the actual password
  parse = JSON.parse(self.value)
  get_pass = parse.last['password']

  # encrypt the password
  crypt = ActiveSupport::MessageEncryptor.new(ENV["SECRET_KEY_BASE"])
  encrypted = crypt.encrypt_and_sign(get_pass)

  # save the new encrypted password
  parse.first['password'] = encrypted
  encrypt_pass = parse.to_json
  self.value = encrypt_pass
end

為了清楚起見,您正在嘗試將記錄中的Main-Hall-Staff密碼和Main-Hall-Guest密碼(所有密碼)更新為自身的加密版本? 我假設在某種形式的before_save回調中調用了此方法? 如果您顯示更多與模型相關的代碼,我可以為您提供更多詳細信息。

def encrypt_pass
  # Changed the name to devises, always use easy to understand naming
  # Also rescuing from a JSON parse error, this isnt always recommended
  # as it hides other errors that might be unrelated to parsing
  devices = JSON.parse(self.value) rescue []
  crypt = ActiveSupport::MessageEncryptor.new(ENV["SECRET_KEY_BASE"])

  devices.each do |device|
    # get the actual password
    password = device['password']

    # encrypt the password
    encrypted_pass = crypt.encrypt_and_sign(password)

    # Save the encrypted password
    device['password'] = encrypted_pass
  end

  self.value = devices.to_json
end

希望您在調用此方法時有一些邏輯,因為您不想加密已經加密的密碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM