簡體   English   中英

Rails中嵌套的ActiveRecord關系

[英]Nested ActiveRecord relationships in Rails

我有很多型號

class User < ActiveRecord::Base
  belongs_to :group
end

class Group < ActiveRecord::Base
  has_many :users
  has_many :posts
end

class Post < ActiveRecord::Base
  belongs_to :group
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :post
end

要獲得用戶的帖子我可以做User.find(1).group.posts.all ,但是如果我想要用戶帖子的所有評論我就不能做User.find(1).group.posts.all.comments.all

除了循環播放所有帖子之外,是否有一個簡單的解決方案來獲取用戶帖子的所有評論?

你想要的是has_many通過關系: http//guides.rubyonrails.org/association_basics.html#the-has-many-through-association

將以下內容添加到您的Group類

has_many :comments, through: :posts

然后你可以得到評論:

User.find(1).group.comments

單一查詢解決方案

Comment.joins(post: {group: :users}).where(users: {id: 1})

結果查詢:

SELECT "comments".* FROM "comments"
  INNER JOIN "posts" ON "posts"."id" = "comments"."post_id"
  INNER JOIN "groups" ON "groups"."id" = "posts"."group_id"
  INNER JOIN "users" ON "users"."group_id" = "groups"."id"
  WHERE "users"."id" = 1

簡單地添加一個has_many :comments, through: :posts是不夠的。 然后,像User.find(1).group.comments這樣的查詢將為您提供用戶組的所有注釋,而不是指定的用戶。

另一種方法是查找給定用戶的所有帖子ID,並使用它來查找該用戶帖子的評論:

post_ids = User.find(1).group.posts.map(&:id).uniq
user_comments = Comment.where(:post => post_ids)

暫無
暫無

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

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