1

2 つのモデルがあるとします。1 つはPostと呼ばれ、もう 1 つはVideoと呼ばれます。次に、これらの各モデルにポリモーフィックに関連付けられた 3 番目のモデル (コメント) があります。

その後、 post.commentsvideo.commentsを簡単に実行して、これらのモデルのレコードに関連付けられたコメントを見つけることができます。ここまではすべて簡単です。

しかし、逆に、コメントが付けられたすべての投稿ビデオを検索し、コメントが作成された日付で並べ替えられたリストに表示したい場合はどうすればよいでしょうか? これは可能ですか?

それが役に立ったら、私は Rails 3 ベータ版に取り組んでいます。

4

2 に答える 2

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 }

これがあなたにとってもうまくいくことを願っています。

編集

また、KandadaBogguが提案したように、あなたが使用していると仮定していますhas_many :comments, :as => :commentablebelongs_to :commentable, :polymorphic => true

編集#2

実際、私は間違いを犯したと思います。上記のコードは機能しません...これを試してください:

(Comment.find(:all, :order => "comment_date")).collect{ |x| x.commentable }
于 2010-03-18T11:53:30.910 に答える
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 に答える