ruby on rails - Hash/Array to Active Record -
i have been searching everywhere can't seem find problem anywhere. in rails 5.0.0.beta3 need sort @record = user.records
association , it's record. sort goes this.
@record = @record.sort_by { |rec| if user.fav_record.find(rec.id) user.fav_record(rec.id).created_at else rec.created_at end
this example of do. sorts fine.
the problem: returns array , not active record class.
i've tried return active record class. i've pushed sorted elements id array , tried extract them in order, i've tried mapping. every result turns previous active record array or hash. need go active record. know how convert array or hash of active record active record class?
there isn't easy way convert activerecord array.
if want optimize performance of app, should try avoid converting arrays activerecord queries. try , keep object query long possible.
that being said, working arrays easier queries, , can feel hassle convert lot of array operations activerecord query (sql) code.
it'd better write sort
code using activerecord::query methods or writing in plain sql using find_by_sql
.
i don't know code should use here, see code refactored clearer. first of all, if
, else
should not capitalized, i'm assuming pseudocode , realize this. second, variable names should pluralized if queries or arrays (i.e. @record.sort_by
should @records.sort_by
instead).
it's worth mentioning activerecord queries difficult master , lot of people use array operations instead since they're easier write. if "premature optimization root of evil", it's not end of world if sacrifice bit of performance , keep array implementation if you're trying make initial prototype. make sure you're not making "n+1" sql calls, i.e. do not make database call every iteration of loop.
here's example of array implementation avoids n+1 sql issue:
# first load user's favorites memory user_fav_records = user.fav_records.select(:id, :created_at) @records = @records.sort_by |record| matching_rec = user.fav_records.find { |x| x.id.eql?(rec.id) } # using array#find, not activerecord method if matching_rec matching_rec.created_at else rec.created_at end end
the main difference between implementation , code in question i'm avoiding calling activerecord's find
each iteration of loop. sql read/writes computationally expensive, , want code make little of them possible.
Comments
Post a Comment