1

假设我有两个模型 - 一个称为Post,另一个称为Video。然后我有第三个模型 -评论- 多态地与这些模型中的每一个相关联。

然后,我可以轻松地进行post.commentsvideo.comments来查找与这些模型记录相关的评论。到目前为止一切都很容易。

但是,如果我想另辟蹊径,我想查找所有已评论的帖子视频,并将其显示在按评论日期排序的列表中?这可能吗?

如果有帮助,我正在开发 Rails 3 beta。

4

2 回答 2

2

尝试这个:

class Post < ActiveRecord::Base
  has_many :comments, :as => :commentable
  named_scope :with_comments, :joins => :comments, 
                              :order => "comments.created_at DESC"
end

class Video < ActiveRecord::Base
  has_many :comments, :as => :commentable
  named_scope :with_comments, :joins => :comments, 
                              :order => "comments.created_at DESC"
end

class Comment < ActiveRecord::Base
  belongs_to :commentable, :polymorphic => true
end

现在您可以运行以下命令:

Post.with_comments
Video.with_comments

编辑 看起来您想要一个包含视频和帖子的列表。这非常棘手,但可行。对于每个页面,您必须执行 3 个查询。

def commented_videos_posts(page = 1, page_size = 30)
  # query 1: get the lastest comments for posts and videos
  comments = Comment.find_all_by_commentable_type(["Post", "Video"], 
               :select => "commentable_type, commentable_id, 
                              MAX(created_at) AS created_at",
               :group => "commentable_type, commentable_id"
               :order => "created_at DESC", 
               :limit => page_size, :offset => (page-1)*page_size)

  # get the video and post ids
  post_ids, video_ids = [], []
  comments.each do |c|
    post_ids << c.commentable_id if c.commentable_type == "Post"
    video_ids << c.commentable_id if c.commentable_type == "Video"
  end

  posts, videos = {}, {}

  # query 2: get posts
  Post.all(post_ids).each{|p| posts[p.id] = p }
  # query 3: get videos
  Video.all(video_ids).each{|v| videos[v.id] = v }

  # form one list of videos and posts
  comments.collect do |c| 
    c.commentable_type == "Post" ? posts[c.commentable_id] :
                                   videos[c.commentable_id]
  end
end
于 2010-03-17T19:00:53.543 回答
2

可能不是最好的方法,但这对我有用:

#get all posts and videos
posts_and_videos = Comment.all.collect{ |c| c.commentable }

#order by last comment date
posts_and_videos_ordered = posts_and_videos.sort{ |x,y| x.comment_date <=> y.comment_date }

希望这也适合你。

编辑

我还假设您正在使用has_many :comments, :as => :commentable并且belongs_to :commentable, :polymorphic => true像 KandadaBoggu 建议的那样。

编辑#2

实际上,我认为我犯了一个错误,上面的代码不起作用......试试这个:

(Comment.find(:all, :order => "comment_date")).collect{ |x| x.commentable }
于 2010-03-18T11:53:30.910 回答