首页 > 解决方案 > 如何根据孩子的记录获取父母

问题描述

我有两个模型

公司.rb

class Company < ApplicationRecord
     has_many :posts
end

post.rb

class Post < ApplicationRecord
    belongs_to :company

    scope :notClosed, -> {where(closed: false)}
    scope :published, -> {where(published: true)}
end

我想获取至少有一个职位与匹配职位的公司scope

目前我的查询是

Company.where(company_type: "Private").all

它返回所有公司,但如何根据我的需要修改此查询。

标签: ruby-on-railsruby

解决方案


published_post_companies = Company.joins(:posts).distinct.merge(Post.published)
notClosed_post_companies = Company.joins(:posts).distinct.merge(Post.notClosed)

推荐阅读