Search code examples
ruby-on-railsparsingruby-hash

Loop through hash and find records to delete in Ruby


I am self-learning ruby by watching few videos and reading through blogs. I am currently in a situation where I have to parse the below parameters that I receive from an external CRM system into RUBY and find the relevant records from the database and delete them. It works well when I get a single record through below code:

temp_id = params[:salesforce_id]
Table.find_or_initialize_by(:id => temp_id).destroy

but I am struggling when I have to parse through multiple records like below, I get this error "ArgumentError (wrong number of arguments (given 0, expected 1)):" I might have to loop through this but any sample code will really help.

{"_json"=>[{"id"=>"1"}, {"id"=>"2"}, {"id"=>"3"}], "delete_record"=>{"_json"=>[{"id"=>"1"}, {"id"=>"2"}, {"id"=>"3"}]}}

Thanks


Solution

  • The structure you have is a Hash (A) having a key "_json" and a key "delete_record" corresponding to a Hash (B) value. This Hash contains a key/value pair with "_json" as the key, and an Array as the value. This Array contains (several) Hash (C) objects.

    What you want here is:

    1. Get the value inside Hash (A) for key "delete_record", which is Hash (B)
    2. Get the value inside Hash (B) for key "_json", which is an Array of Hash objects (C)
    3. For each Hash (C) inside the Array, get the value for the key "id".

    You can do the following:

    data = {
      "_json"=>
        [{"id"=>"1"}, {"id"=>"2"}, {"id"=>"3"}], 
      "delete_record"=>
        {"_json"=>[{"id"=>"1"}, {"id"=>"2"}, {"id"=>"3"}]}
    }
    # step 1
    data_for_delete_record_key = data['delete_record']
    # step 2
    array_of_hashes_with_id_key = data_for_delete_record_key['_json']
    # step 3
    ids_to_destroy = array_of_hashes_with_id_key.map { |hash| hash['id'] }
    

    Then, you can simply use the following to destroy the matching records:

    Table.where(id: ids_to_destroy).destroy_all