簡體   English   中英

在 Rails 中加載關聯的最高效方式

[英]Most performant way to load associations in rails

我正在嘗試加載一個嵌套關聯,一個User可以屬於多個Groups ,我想加載用戶所屬Groups中的所有Posts ,但也只有帖子沒有組。

類似於current_user.groups.eager_load(:posts) ,但沒有在組下嵌套帖子。

我假設Post在這里屬於Group

從您需要加載的 model 開始,並從那里構建查詢。 如果用戶在這里屬於 2 個組,這將加載這 2 個組中的所有帖子。

Post.where(group: current_user.groups)

您可以使用has_many:through設置從UserPost的快捷方式

class User < ApplicationRecord
  has_and_belongs_to_many :groups
  has_many :posts, through: :groups

  # if User already has a `has_many :posts`, you'll need 
  # to give the through-association a unique name like this:
  # has_many :group_posts, through: :groups, source: :posts
end

class Group < ApplicationRecord
  has_and_belongs_to_many :users
  has_many :posts
end

class Post < ApplicationRecord
  belongs_to :group

  # optionally, you can define the inverse here as well
  # has_many :users, through: :group
end
...

# eager_load on a query: User.includes(:posts) or User.eager_load(:posts)
# get from current user: current_user.posts

暫無
暫無

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

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