0

I have a Match and User model with a has_and_belongs_to_many between them.

How do I retrieve match.users.first and match.users.second based on when the MatchUser association was created, rather than by when the User itself was created?

Matt Langan
  • 119
  • 7

2 Answers2

1

You don't want to be using has_and_belongs_to_many in the first place. has_and_belongs_to_many relations are headless - there is no join model. The only columns that are ever used on the join table are the two foreign keys. Even if you added a created_at column to the join table there is no way to access it or use it to order the records. And AR won't set the timestamps anyways.

While you can kind of assume that a has_and_belongs_to_many association is ordered in the same order that the records where inserted you can't really order it.

You want to use has_many through: which uses a model to join the two records:

class User < ApplicationRecord
  has_many :user_matches
  has_many :matches, through: :user_matches
end

class Match < ApplicationRecord
  has_many :user_matches
  has_many :users, through: :user_matches
end

class UserMatch < ApplicationRecord
  belongs_to :user
  belongs_to :match
end

You can then order the association by:

match.users.order("user_matches.created_at DESC")
max
  • 96,212
  • 14
  • 104
  • 165
-1
match.users.first

will return the first user by :id.

If you want to it ordered by created_at then you must do something like

user_id = matches_users.where(match_id: match.id).first.user_id
user.find(user_id)

Hope this is what you are looking at.

Vikram Sharma
  • 526
  • 5
  • 14