0

I am working with an array in this form:

"car_documents_attributes"=>{ "1562523330183"=>{ "id"=>"", "filename"=>"tyYYqHeqSFOnqLHEz5lO_rc_tispor12756_6wldwu.pdf", "document_type"=>"contract" }, "1562523353208"=>{ "id"=>"", "filename"=>"a9P8TyECRiKbI2YdRVZy_rc_tispor12756_bbtzdz.pdf", "document_type"=>"request" }, "1562523353496"=>{ "id"=>"", "filename"=>"WCM5FHOfSw6yNSUrfPPm_rc_tispor12756_dqu9r2.pdf", "document_type"=>"notes" }, ... } 

I need to find out if in this array is an item where document_type=contract (there can be none, one or multiple ones).

The way I do it is looping through the array item by item, which can be slow if there are tens of items.

Is there a better and faster way to simply check if in the array is an item with document_type = contract?

1
  • There is no array in your example. Commented Jul 8, 2019 at 6:59

1 Answer 1

2

That's a hash containing more hashes. What you can do is to access to car_documents_attributes, iterate over those hash values and check if any document_type is "contract":

data = { "car_documents_attributes" => { "1562523330183" => { "id" => "", "filename" => "tyYYqHeqSFOnqLHEz5lO_rc_tispor12756_6wldwu.pdf", "document_type" => "contract"}, "1562523353208" => { "id" => "", "filename" => "a9P8TyECRiKbI2YdRVZy_rc_tispor12756_bbtzdz.pdf", "document_type" => "request" }, "1562523353496" => { "id" => "", "filename" => "WCM5FHOfSw6yNSUrfPPm_rc_tispor12756_dqu9r2.pdf", "document_type" => "notes" } } } p data['car_documents_attributes'].any? { |_, doc| doc['document_type'] == 'contract' } # true 

Didn't know it was data coming from the params. If so, you do need to permit what's being received or convert the params to an unsafe hash.

Also, you can try using fetch instead [] when trying to get car_documents_attributes, because if that key isn't in data, it'll throw nil, which would throw a NoMethodError:

data.fetch('car_documents_attributes', []).any? { |_, doc| doc['document_type'] == 'contract' } 
Sign up to request clarification or add additional context in comments.

2 Comments

thank you. However, I needed to add to_unsafe_h, because the code was throwing error rails undefined method any?' for #<ActionController::Parameters:. -> data['car_documents_attributes'].to_unsafe_h.any? {...`
Yes, ActionController::Parameters is a different implementation which needs to be converted to an "unsafe" hash in order to invoke some methods. See the edit.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.