コメントには通常のポリモーフィックな関連付けがあります。
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を定義できるようにしたいと思います。今、私はネストされたselectでこれを行うためのかなり醜いfind_by_SQLクエリを見ています。SQLに頼らずにRailsでそれを行うためのより良い方法があるに違いないようです。
何か案は?ありがとう。
その価値については、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;