Rails multiple querys

I have this set of tables (I’m using postgresql)

User (with id, first_name, …)
Assignment (with id, name, start_date, finish_date,…)
AssignmentUser(with assignment_id, user_id, flag_status)
The flag_status is a boolean that says if a user is still or not in an
assignment.

Let’s say user1 applies for assignment1, assignment2, assignment3 as
follows:

                              start_date     finish_date

flag_status
user1 assignment1 11-11-11 11-12-11 false
user1 assignment2 01-10-11 01-02-12 true
user1 assignment3 01-01-12 01-03-12 true
Let’s say I want to search TODAY the closest start_date of an user’s
assignment.

I’ve done this in my User model:

def last_date
self.assignments.where(“date < ?”, Date.today).max.try(:date)
end
and this

def last_status

AssignmentUser.find_by_assignment_id_and_user_id(Assignment.find_by_date(self.last_date),
self.id).flag_status if self.last_date.present?
end
And in my view for each user:

User.all.each do |u|

u.first_name u.last_email u.last_status end It works well but, in my log I see 3 queries for each user (as expected). So my question is: how can I avoid these multiple queries?

Thanks in advance

Javier

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs