ruby on rails - Is there a good pattern for combining ActiveRecord results with API data? -


what best way combine 2 data sets different locations?

i have 1 set of data activerecord merge/combine data set api. both data sets have unique id common between them merge based on id , avoid duplicate results.

since unifying these data display purposes, it's better use helper arrange data structure view needs it.

controller:

@model_records = armodel.find_my_scope @api_records = apigem.gather_users 

helper:

def all_users   ar_prop_filter = [:username, :first_name, :last_name, :current_project]   api_prop_filter = ['ranking', 'postcount', 'username', 'first_name', 'last_name']    # reduce hashes   model_set = @model_records.map{|rec| ar_prop_filter.inject({}){|acc, f| acc[f] = rec.send(f)} }    api_set = @api_records.map{|rec| api_prop_filter.inject({}){|acc, f| acc[f.to_sym] = rec[f]} }    # add api data ar data, using ar key   model_set.map! |m_rec|     api_set[m_rec[:username]].each |k, v|       m_rec[k] = v     end   end    # add api data not represented in ar data   model_set += api_set.reject{|k, v| model_set.keys.include? k}    return model_set end 

this method has inefficiencies, , assumes different data between sources, leading gaps wold need anneal or validate views


remember think of best-practices mvc models - otherwise begs question why it.

this principally problem because active record object not simple hash. instantiation of class, , merging data lead unexpected results. if use library access , api, library may instantiate objects – lead similar problems.

if have case demands doing things described, best represent cast each of api , active record objects hashes, , .merge them together. remember have key space collisions when doing this, , lose data.

remember when converting hashes have no simple nor performant way read save data active record or api source.


cheers


Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -