ruby - Find Value in Array of ActiveRecord Objects vs. Find Value from Repeated DB Calls -
i return true, if array of contact(s) (model) contains contact id equal value. example:
@contacts = contact.all @someval = "alskjdf" find_val(@contacts, @someval) def find_val(contacts, val) @contact.each |c| if c.id == val return true end end return false end i have repeatedly in app (at 100 times particular actions), in order exclude data external api has list of contacts. going expensive?
i thought might able faster, similar activerecord find on array after it's been pulled down db, can't figure out. expensive call activerecord this?
contacts.find_by_id(@someval) the above line have called hundreds of times... figure iterating through array less expensive. thanks!
the best approach index contacts in hash, using contact id key after retrieve them db:
contacts = contact.all.inject({}) {|hash, contact| hash[contact.id] = contact; hash } then can contact contact[id] in performant way.
Comments
Post a Comment