的時間戳我有意見平常多態關聯來獲得最新項目:的Rails:查詢基於多態關聯
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
我希望能夠定義Book.recently_commented,和文章。 recent_commented基於評論的created_at時間戳。現在我正在尋找一個非常難看的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;
你可以重構Time.now - 5.分鐘由5.minutes.ago :) – hellvinz 2010-09-13 16:54:55
謝謝,這讓我在那裏!我正在使用acts_as_commentable,所以我的下一個任務是將其添加到插件中,因此我不必爲每種類型重複該操作。 – 2010-09-13 18:30:33
沒問題。更新以包含'.ago'的細化。 – Shadwell 2010-09-13 19:01:41