ruby on rails - Finding records which includes an id in an array attribute of the records -
i have exam
model lang_array
field
exam.last.lang_array #=> "1,2,5"
i want find exams have particular id. able single exam this:
exam.last.lang_array.split(',').map(&:to_i).include? 1
how possible exams , find records efficiently?
you can't perform search efficiently when serialize list of ids in single database column. in order perform efficient lookup databases use index, can't index aggregate data in way.
the way should construct database relationship. if exam model can have many "lang", add new table represent such relationship. if id represented lang database model, become many many relationship.
you can add instance model examlang have 2 fields: id of exam , id of lang. each record represents single relationship.
when want fetch exam include specific lang id, easy simple sql select statement.
there no efficient way lookup exam lang id otherwise. have perform full scan (both full db table scan , entire loop on ruby side) inefficient.
Comments
Post a Comment