活动记录 - 从has_and_belongs_to_many和has_many获取相关记录

问题描述 投票:1回答:1

我正在使用ruby活动记录

class Blog < ActiveRecord::Base
  has_and_belongs_to_many :users
end

class User < ActiveRecord::Base
  has_and_belongs_to_many :blogs
  has_many :posts
  has_many :comments
end

class Post < ActiveRecord::Base
  belongs_to :user
end

class Comment < ActiveRecord::Base
  belongs_to :user
end

我如何获得至少有1个帖子或1条评论的博客用户

伪代码中有类似的东西

Blog.users.where(posts.count > 1 || comments.count > 1)
ruby-on-rails ruby activerecord
1个回答
0
投票

我相信你应该能够使用以下内容,但无法测试:

users = Blog.users
users.left_outer_joins(:posts).where.not(posts: { user_id: nil })
  .or(
    users.left_outer_joins(:comments).where.not(comments: { user_id: nil })
  )

# or if you're on Rails < 5
query = <<-SQL
  SELECT users.* from users
  LEFT OUTER JOIN posts ON posts.user_id = users.id
  LEFT OUTER JOIN comments ON comments.user_id = users.id
  WHERE posts.user_id IS NOT NULL
  OR comments.user_id IS NOT NULL
SQL

users.where(query)

简而言之,这坚持在查询中存在user_id的帖子和评论。这在检查是否存在一个关联时肯定有效,尽管我没有尝试使用or

我现在有一个旧版本的Rails运行,并且很想知道这是否能像我期望的那样工作,所以如果你能让我知道你如何使用@ user2624242,那就太好了。

© www.soinside.com 2019 - 2024. All rights reserved.