簡體   English   中英

兩個has_many關聯到同一模型

[英]Two has_many associations to the same model

我有一個博客模型,其中包含許多帖子,其中一些帖子是熱門帖子。 我的意圖是擁有類似以下內容的東西。

class Blog
  has_many :posts
  has_many :top_posts, class_name: 'Post'
end

class Post
  belongs_to :blog
end

如您所見,帖子和頂部帖子是相同的對象,但是頂部帖子的集合與帖子的集合不同。 有些帖子也是熱門帖子,但其他帖子不是。

問題是當我嘗試執行blog.top_posts ,它返回與blog.posts相同的集合,這些集合都是該博客中的所有帖子。 我希望blog.top_posts僅返回我通過blog.top_post_ids << random_post與該博客的頂級帖子相關聯的帖子。 提前致謝!

我會假設,就像David在評論中問您一樣,您有特定的帖子。

例如,如果一個帖子有50個頂,1000個視圖,或者在數據庫中具有永久屬性,則該帖子可能成為top_post。

如果您的數據庫上沒有任何永久性條件,則不能使用活動記錄獲取top_post。 無論如何,您應該使用范圍:

 class Blog
  has_many :posts

 end

class Post
  belongs_to :blog
  scope :top_posts, -> { where(views > 1000 ) }  #or any conditions base on your criterias
end

您可以簡單地獲得它們:

    blog = Blog.first
    blog.posts.top_posts # => [top posts belonging to this blog]

這是基於假設的答案...

適用范圍的文檔: http : //guides.rubyonrails.org/active_record_querying.html#scopes

使用has_many的問題是,它只是將Blog對象的ID附加到每個Post對象,因此,當您調用blog.postsblog.top_posts它會執行SQL查詢以查找Posts WITH id=Blog.id從而獲得相同的列表兩次。

我建議您只有一個has_many posts ,然后對使每個帖子都成為“熱門帖子”的原因返回的列表進行排序。 或者,如果您想避免排序,建議您輸入以下內容:

class Blog
  has_many :posts

  def initialize
    @top_posts = []
  end

  def add_top_post(post)
    if self.posts.include?(post)
      @top_posts << post
    end
  end
end

class Post
  belongs_to :blog
end

范圍如何? http://guides.rubyonrails.org/active_record_querying.html#scopes

class Blog
      has_many :posts
    end

    class Post
      belongs_to :blog
      scope :top, -> { where top_post: true }
    end

    # this gets all the top posts
    blog.posts.top

暫無
暫無

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

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