簡體   English   中英

Rails N + 1查詢問題時獲取與where條件關聯的記錄

[英]Rails N + 1 query problem when fetching associated records with where condition

我有下表結構。 這只是一個例子

UserPost => user_id, post_id, Post, Comment

因此,如果我嘗試使用以下查詢獲取所有user_posts並在comments表上執行位置,那么它會觸發對comments表的查詢

user_posts = UserPost.includes(post: :comments)
user_posts.each do |up|
  post = up.post # No Query
  comments = up.comments # No query
  comments_with_condition = up.comments.where(visibility: true).order(position: :asc).first.data # Fires query for .where and .order as well.
end

那么,這是預期的行為還是我做錯了什么?

如何防止對每個user_post的查詢

您可以做的是在您的 model 中添加另一個has_many ,並使用您想要的過濾器。

# You can name this anything you want but a descriptive name helps
has_many :special_comments, -> { where(visibility: true).order(..) }, class_name: 'Comment'

...並在您的查詢中急切加載,這將急切加載兩種類型的評論。 這不可避免地會導致一個額外的查詢,但它不是N+1。

user_post = UserPost.includes(post: [:comments, :special_comments])

user_posts.each do |user_post|
  post = user_post.post
  comments = user_post.comments
  comments_with_condition = user_post.special_comments
end

暫無
暫無

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

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