Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get distinct polymorphic association

I'm trying to get show a list of polymorphic relations without having any duplicates.

I have a StoreViews table with a polymorphic field called viewable (so there's a viewable_id and viewable_type column in my table). Now I want to display views with each polymorphic relation showing up just once, without duplicates.

@views = StoreView.
    .distinct(:viewable_id)
    .distinct(:viewable_type)
    .order("created_at DESC")
    .limit(10)

So if there's two records in StoreViews, both with the same viewable relation, @views should only return the most recent one. However, this is not the case.

like image 896
NathanB Avatar asked Dec 21 '18 07:12

NathanB


People also ask

How is polymorphic association set up in Rails?

In Ruby on Rails, a polymorphic association is an Active Record association that can connect a model to multiple other models. For example, we can use a single association to connect the Review model with the Event and Restaurant models, allowing us to connect a review with either an event or a restaurant.

What is a polymorphic association in rails?

Polymorphic relationship in Rails refers to a type of Active Record association. This concept is used to attach a model to another model that can be of a different type by only having to define one association.


1 Answers

ORDER BY items must appear in the select list if SELECT DISTINCT is specified. There are several ways to work around this issue.

In this example using an aggregate function should work:

@views = StoreView
           .select('DISTINCT viewable_type, viewable_id, MAX(created_at)')
           .group(:viewable_type, :viewable_id)
           .order('MAX(created_at) DESC')
           .limit(10)
like image 85
spickermann Avatar answered Sep 29 '22 08:09

spickermann