0

I have an ActiveRecord relation for a many-to-many relationship and I would like to return a collection of the unique items from one side of the relationship.

Ideally, I would like to do this together, but I'm aware this might not be possible.

The key thing I'm trying to do is remove duplicates based on the foreign key, without losing the additional data by calling select(:foreign_key).distinct and while preserving the ActiveRecord_Relation type to allow further queries.

As an example:

Article.first.comments returns 10 comments from 6 commenters (alias for users). Article.first.comments.select(:commenter_id).distinct returns the 6 commenters but loses the time stamps.

I want a way to get all the commenters for the Article ordered by when they left the comment.

Phil-6
  • 552
  • 6
  • 16

1 Answers1

0

Twitter had a few good suggestions:

has_many :commenters, -> { distinct }, through: :comments (Credit @bensheldon)

@Appwerks Pointed to this StackOverflow answer which was a good start.

I simplified my problem slightly for the sake of explanation, the first answer works well in the case in my question, but I'm actually dealing with a polymorphic relationship and a few other complexities.


The solution I've ended up with:

def article_commenters
  commenter_ids = Article.first.comments.pluck(:commenter_id)
  User.where(id: commenter_ids)
end
Phil-6
  • 552
  • 6
  • 16