Ganesh Kunwar
Ganesh Kunwar

Reputation: 2653

Rails activerecord query with has_many belongs_to association

I have two ActiveRecord models: User and Course. Which are associated as following:

class User < ActiveRecord::Base
  has_many :courses
end

class Course < ActiveRecord::Base
  belongs_to :user
end

Now my question is: how can I get the last course of each user?

I tried following:

courses = Array.new
User.find_each { |u| courses << u.courses.last }

But I'm doubt on its performance. So looking for best solution with good performance.

Thanks in advance.

Upvotes: 0

Views: 594

Answers (5)

Terry Raimondo
Terry Raimondo

Reputation: 639

To get the last course of each User you can do this:

courses = []
User.includes(:courses).find_each { |u| courses << u.courses.last }

Upvotes: 1

An other way with 1 SQL query

Course.all.group_by(&:user_id).map { |_k,courses| courses.last }

Upvotes: 1

VictorTpo
VictorTpo

Reputation: 66

In 2 requests :

User.select(:id).includes(:courses).each { |u| u.courses.last }

Doesn't work if your tables are too big

Upvotes: 1

Albin
Albin

Reputation: 3032

I still think that it might be easier to just accept 2 queries. But I found the article I looked at before deciding to do it in 2 queries. This works but it adds quite a bit of complexity.

Rails Associations has_one Latest Record

Upvotes: 1

Marco Roth
Marco Roth

Reputation: 184

Like that you can find out the last course for a user

User.find(1).courses.order(name: :ASC).last

If you want to have an array:

courses = []

User.each do |u|
   courses << u.courses.order(name: :ASC).last
end

Upvotes: -2

Related Questions