If I have a polymorphic association between 3 models as:
Comment
belongs_to :book, :class_name => 'Book', :foreign_key => 'ref_id', conditions: "comments.ref_type = 'Book'"
belongs_to :article, :class_name => 'Article', :foreign_key => 'ref_id', conditions: "comments.ref_type = 'Article'"
belongs_to :ref, :polymorphic => true
How can I pick distinct values from Title
column of both Book
and Article
models for a given list of comments?
For example, if I have to list the titles for books and article for which comments have been given in a time period then how can I do that? I can easily pick the comment list but how do I pick related unique titles from Book
and Article
?
For example:
Book
+--------------+
| Id | Title |
+----+---------+
| 1 | 'Book1' |
| 2 | 'Book2' |
| 3 | 'Book3' |
+--------------+
Article
+-----------------+
| Id | Title |
+----+------------+
| 1 | 'Article1' |
| 2 | 'Article2' |
+-----------------+
Comments
+--------------------------------------+
| Id | comment | ref_id | ref_type |
+----+------------+--------+-----------+
| 1 | 'comment1' | 1 | Book |
| 2 | 'comment2' | 1 | Book |
| 3 | 'comment3' | 1 | Article |
| 4 | 'comment4' | 3 | Book |
+--------------------------------------+
I need the list of title to be 'Book1'
, 'Book3'
, 'Article1'
.