0

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

4

2 回答 2

1

您拥有的结构是一个Hash(A),它有一个键"_json"和一个"delete_record"对应于Hash(B) 值的键。这Hash包含一个键/值对,其中"_json"作为键,Array作为值。这Array包含(几个)Hash(C)对象。

你在这里想要的是:

  1. 获取 key 的 Hash (A) 内的值"delete_record",即 Hash (B)
  2. 获取 Hash (B) 中 key 的值"_json",这是一个 Hash 对象数组 (C)
  3. 对于 Array 中的每个 Hash (C),获取 key 的值"id"

您可以执行以下操作:

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'] }

然后,您可以简单地使用以下内容来销毁匹配的记录:

Table.where(id: ids_to_destroy).destroy_all
于 2018-03-20T14:13:20.427 回答
0

尝试使用:

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

temp_id["delete_record"]["_json"].pluck("id").each do |x|
  Table.find_or_initialize_by(:id => x.to_i).destroy
end
于 2018-03-20T13:58:59.170 回答