简体   繁体   English

从关联模型中选取

[英]Plucking from an Associated Model

I have two models, User and Post . 我有两个模型, UserPost Post belongs to User . Post属于User User has a field titled name . User有一个名为name的字段。 I want to pluck the names of users. 我想摘取用户名。 I was thinking of doing something like this. 我当时正在考虑做这样的事情。

some_cool_posts = Post.limit(5)

some_cool_posts.map(&:user).pluck(:name)

Unfortunately, pluck doesn't work with arrays so then I do 不幸的是,pluck不适用于数组,所以我可以

some_cool_posts.map(&:user).map(&:name)

I'm wondering is there a faster way to do this in Rails? 我想知道在Rails中有更快的方法吗?

You have 6 requests to db, if use includes() then you will have two requests 您有6个对db的请求,如果使用include(),那么您将有两个请求

some_cool_posts = Post.includes(:users).limit(5)
some_cool_posts.map(&:user).map(&:name)

And you can get posts with usernames, for one request, like: 对于一个请求,您可以获取带有用户名的帖子,例如:

some_cool_posts = Post.joins(:user).select('posts.*, users.name as user_name').limit(5)
some_cool_posts.map &:user_name

and, imho, the most faster way: 而且,恕我直言,最快的方法是:

some_cool_posts = Post.limit(5)
uids = some_cool_posts.map &:user_id
User.where(id: uids).pluck :name

If I am understanding you correctly, you can also do: 如果我对您的理解正确,也可以执行以下操作:

@posts_users = some_cool_posts.collect {|post| post.user }
@users_names = @posts_users.collect { |user| user.name }

and you can try shortening it to this, but i'm not sure this will work: 您可以尝试将其缩短为这个值,但是我不确定这是否可行:

@users_names = some_cool_posts.collect {|post| post.user }.collect { |user| user.name }

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

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