簡體   English   中英

如何在Active Record中從關聯到關聯模型的關聯

[英]How to go from a relation to a relation of associated model in Active Record

我經常遇到這種情況

class Post
   has_many :comments

end

現在,如果我有一個帖子關系,我將如何獲取該帖子上所有評論的關系。

我正在尋找的是

Post.where(user: user).comments

但這行不通。 我在這里錯過明顯的東西嗎? 這似乎是一個常見的用例。

基本上,當您執行Post.where(user: user).includes(:comments)我們已經預加載了所有必需的注釋,我想要的是直接訪問它們,而無需Post.where(user: user).includes(:comments).map{|p| p.comments}.flatten.uniq Post.where(user: user).includes(:comments).map{|p| p.comments}.flatten.uniq或類似的內容。

我會定義一個范圍

scope :comments_in_user_posts, -> (user) { where(user: user).includes(:comments).map{|p| p.comments}.flatten }

然后像Post.comments_in_user_posts(user)一樣使用它。

編輯:

另一種選擇是使用Comment.where(post: Post.where(user: user))

您還可以在Post模型中創建靜態方法:

def self.user_comments(user)
    Comment.where(post: Post.where(user: user))
end

然后致電:

Post.user_comments(user)

如果要獲取comment對象,請在Comment類中實現邏輯。

您可以如下定義范圍:

class Comment < ActiveRecord::Base
  belongs_to :post

  scope :from_user, ->(user_id) { joins(post: :user).where(users: {id: user_id} }
end

這樣你就可以打電話

Comment.from_user(current_user.id)

您需要在注釋模型中提到,屬居到:post。

    class Comment < ActiveRecord::Base
      belongs_to :post  
    end

現在,當您保存與帖子相關的任何評論時。 確保@post對象存在。

            @post.comments.create(name: "New comment")

您可以嘗試在Rails控制台中檢查其中的內容。 現在,當您看到注釋對象時。 它應該有post_id存在。 所以現在

post_obj.comments

提供評論數組和comment.post將提供相關的帖子。

暫無
暫無

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

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