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
source share