Please help me with think of a better algorithm in Ruby on Rails -


i have events, people. there many-to-many relationship between them there personevent connecting events people.

event has date , type

personevent has event_id , person_id

person has name

i'm trying build search form allows user search type of event, , returns list of people attended event of type in past , last date attended such event. should in controller.

the solution can think of involves nested loops , run slowly. i'm looping through lot of things don't need be.

for each person in person.all     each personevent in personevent.all         add personevent array if person_event.event.type correct     now, loop through array , find event latest date. that's date of last event attendance. 

can suggest better algorithm?

as have associations set should able like:

f = person.joins(:events) f = f.where(:events => { :type => "the_type_you_are_searching_for" }) f = f.group('people.id') f = f.select('people.*, max(events.date) last_event_date') people = f.all # though want paginate 

i've done line line make easier read in here you'd see where, group , select chained 1 after other on same line.

you need group otherwise you'll people returned multiple times if have been multiple events.

the custom select include last_event_date in results.


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -