簡體   English   中英

反向的多態關聯

[英]Polymorphic association in reverse

假設我有兩個模型 - 一個叫Post ,另一個叫Video 然后我有第三個模型 - 評論 - 與每個模型的多態關聯。

然后,我可以輕松地發布post.comvideo.com以查找與這些模型的記錄相關的評論。 到目前為止都很容易。

但是,如果我想轉向其他方式並且我想查找已經評論過的所有帖子視頻並將其顯示在按評論發布日期排序的列表中,該怎么辦? 這可能嗎?

如果它有助於我正在開發Rails 3 beta。

嘗試這個:

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

可能不是最好的方式,但這對我有用:

#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 => :commentablebelongs_to :commentable, :polymorphic => true就像KandadaBoggu建議的那樣。

編輯#2

實際上,我認為我犯了一個錯誤,上面的代碼將無法正常工作...試試這個:

(Comment.find(:all, :order => "comment_date")).collect{ |x| x.commentable }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM