How do you query the most recent record of different objects and display in a list?

Viewed 20

Need help with an active record query in ruby on rails app with postgres

  • I have "Customers" who have many "Notes".
  • I want to grab the most recent note that each customer made.
  • Then display a list of those notes from oldest to newest

My current query is

    @all_notes = Note.where("account_note = ?", false).order(created_at: :desc)

Thank you

1 Answers
notes = []

# Eager load notes and get all users with at least one note
users = User.all.includes(:notes).where.not(notes: 
{ id: nil })

# Iterate through each user and get their most recent note
users.each do |user|
  notes << 
user.notes.order("created_at").last
end

# Sort notes array by oldest to newest
notes.sort_by(&:created_at)

There may be a more efficient way, but this is one way to get what you are looking for

Related