我对评论有通常的多态关联:
class Book < ActiveRecord::Base
has_many :comments, :as => :commentable
end
class Article < ActiveRecord::Base
has_many :comments, :as => :commentable
end
class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true
end
我希望能够根据评论上的 created_at 时间戳定义 Book.recently_commented 和 Article.recently_commented。现在我正在查看一个非常丑陋的 find_by_SQL 查询来使用嵌套选择来执行此操作。似乎必须有更好的方法在 Rails 中完成,而无需求助于 SQL。
有任何想法吗?谢谢。
对于它的价值,这里是 SQL:
select * from
(select books.*,comments.created_at as comment_date
from books inner join comments on books.id = comments.commentable_id
where comments.commentable_type='Book' order by comment_date desc) as p
group by id order by null;