我正在使用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)
我相信你应该能够使用以下内容,但无法测试:
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,那就太好了。