通过has_many关系获得所有收集的孩子

时间:2015-09-17 20:38:49

标签: ruby-on-rails rails-activerecord

如果我有一个Post的集合,那么无论如何都要使用方法链或范围来获取所有这些帖子的所有Comment吗?

例如:

posts = Post.where(published: true)
comments = posts.comments

# vs 
comments = []
posts.each do |post|
  comments.push(post.comments)
end

2 个答案:

答案 0 :(得分:7)

当然,有几种方法。您可以使用mapflatten,这对少数记录很有用。请务必使用includes批量加载评论。

Post.where(published: true).includes(:comments).map(&:comments).flatten

或者您可以使用联接。这会在数据库上投入更多工作,这可能会更快,但取决于您的架构和数据集。您通常希望使用uniq来防止重复。

posts = Post.where(published: true)
Comment.joins(:post).merge(posts).uniq

此外,请确保您完全限定联接表中任何子句中的任何显式片段,例如使用where('posts.created_at < ?', ...)代替where('created_at < ?', ...)

修改

第一个的另一个变体,如果你想返回一个关系(可以进一步缩小界限):

Comment.where(id: Post.where(published: true).pluck(:id))

答案 1 :(得分:3)

最佳方式:

$table_prefix = ‘wp_’;
define(‘CUSTOM_USER_TABLE’, $table_prefix.’global_users’);
define(‘CUSTOM_USER_META_TABLE’, $table_prefix.’global_usermeta’);

define(‘WP_ALLOW_MULTISITE’, true);

或者如果您的Comment.joins(:post).where(post: {published: true}) 变量是ActiveRecord Relation:

posts