Order by polymorphic belongs_to attribute

How to make an ActiveRecord request that orders an attribute of a polymorphic membership in an association?

For example, I have a model called Tagging that has a polymorphic association with the name tagged_item .

Unfortunately, Tagging.joins(:tagged_item) throws a ActiveRecord::EagerLoadPolymorphicError . Therefore, I cannot do something like Tagging.joins(:tagged_item).order("tagged_item.created_at DESC") .

Any suggestions?

+4
source share
1 answer

You cannot directly relate to a polymorphic relation, because the data of polymorphic objects are in different tables. However, you can try to do this manually, as in the following example.

 class Tagging < ActiveRecord::Base belongs_to :tagged_item, :polymorphic => true end class Post has_many :image_tagging, :as => :tagged_item end class Comment has_Many :image_tagging, :as => :tagged_item Tagging.select("taggins.*, COALESCE(posts.created_at, comments.created_at) AS tagged_item_created_at"). joins("LEFT OUTER JOIN posts ON posts.id = tagging.tagged_item_id AND tagging.tagged_item_type = 'Post'"). joins("LEFT OUTER JOIN comments ON comments.id = tagging.tagged_item_id AND tagging.tagged_item_type = 'Comment'"). order("tagged_item_created_at DESC") 

COALESCE selects the first column if it exists differently than the other. This is the same as IFNULL in mysql, or you can even use CASE WHEN ... IS NULL THEN ... ELSE ... END

0
source

All Articles