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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With