简体   繁体   中英

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.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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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