【发布时间】:2017-06-26 19:58:30
【问题描述】:
如果我在 3 个模型之间存在多态关联:
评论
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
对于给定的 cmets 列表,我如何从 Book 和 Article 模型的 Title 列中选择不同的值?
例如,如果我必须列出某个时间段内已获得 cmets 的书籍和文章的标题,那么我该怎么做?我可以轻松选择评论列表,但如何从 Book 和 Article 中选择相关的唯一标题?
例如:
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 |
+--------------------------------------+
我需要标题列表为'Book1'、'Book3'、'Article1'。
【问题讨论】:
-
如果你发布一个例子,它会让别人更容易帮助你。
-
你的联想对我来说没有意义。 Comment 的 ref_id 列与 Article 和 Book 的主键有什么关系?
-
我在定义关联时有 :foreign_key => 'ref_id'。
标签: ruby-on-rails polymorphic-associations distinct-values