I have a page where I start with a list of check_ins or client visits and then I need to loop through each visit (i) to find all that client's other visits to determine the visits neighbor (i - 1). I need to pull information from that visits neighbor as well. This is taking a very long time and I thought there might be a speedier way to perform the query.
Assuming I start with the list of visits or check_ins:
check_ins.each_with_index do |ci, i|
# access the client
client = ci.client
# pull other relevent client visits
client_cis = client.check_ins
.visible
.includes(:weigh_in)
.select(:id, :week, :created_at, :type_of_weighin)
.where.not(check_ins: {type_of_weighin: nil})
.where.not(weigh_ins: {id: nil})
.where("weigh_ins.date >= ?", ci.created_at - 3.weeks)
# access the visit's index
i = client_cis.index(ci)
# access the visit's neighbor
neighbor = client_cis[ i - 1 ]
# perform downstream calculations using visit and it's neighbor
...
end
Is there a faster way to perform this type of analysis?
You could try this although I make no performance improvement guarantees the following should result in the same functional mechanism
UPDATE to explain what this code does per the OP's request:
grouped_check_ins = check_ins.group_by(&:client_id)- group yourCheckInobjects by the client_id for faster lookup. This results in aHashof{client_id => [CheckIns]}Arel work - This is so we can build a join with multiple conditions. In this case the conditions are "weigh_ins.check_in_id = check_ins.id AND weigh_ins.date >= check_ins.created_at - interval '3 week'"
This results in SQL akin to