簡體   English   中英

Rails:從關聯模型中獲取所有用戶

[英]Rails: Getting all users from an associated model

說我有一個文章模型,用戶模型和評論模型。 如果我想讓所有對特定文章發表評論的用戶是最好的方法,還是有更好的方法?

User.find(Article.first.comments.pluck(:user_id))

您有幾種選擇。

你可以加

has_many :users, through: :comments

Article然后說:

@article.users

如果由於某種原因您不想這樣做,可以這樣做

@article.comments.collect(&:user)

我認為這樣會更有效:

@article.comments.includes(:users).collect(&:user)

希望對您有所幫助。

暫無
暫無

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

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