简体   繁体   English

Rails:从关联模型中获取所有用户

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

Say I have an article model, user model and comment model. 说我有一个文章模型,用户模型和评论模型。 If I want to get all users that commented on a particular article is this the best way or is there a better way? 如果我想让所有对特定文章发表评论的用户是最好的方法,还是有更好的方法?

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

You have a few options. 您有几种选择。

You can add 你可以加

has_many :users, through: :comments

to Article then just say: Article然后说:

@article.users

If you don't want to do that for some reason you can do 如果由于某种原因您不想这样做,可以这样做

@article.comments.collect(&:user)

I think this would be more efficient: 我认为这样会更有效:

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

I hope that helps. 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM