ruby-on-rails - 如何根据孩子的记录获取父母
问题描述
我有两个模型
公司.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
它返回所有公司,但如何根据我的需要修改此查询。
解决方案
published_post_companies = Company.joins(:posts).distinct.merge(Post.published)
notClosed_post_companies = Company.joins(:posts).distinct.merge(Post.notClosed)
推荐阅读
- tensorflow - 在 Tensorflow 中重新训练 SavedModel
- bash - Bash 构建多个逗号分隔的列表,限制为一个更大列表中的 N 个项目
- javascript - React, Javascript - 捕获浏览器/标签关闭事件
- graphql - GraphQL 查询,具有动态字段
- python - 为什么我的 python 程序在使用调试器运行时不会抛出错误?
- python - 循环删除字典项
- javascript - 单击导航链接时运行相同的功能(vanilla JS)
- sql-server - 存储过程在插入新行时返回 NULL 输出值
- javascript - 基本视差效果违背物理学
- google-apps-script - 如何使用 google sheet api v 4 将 blob(图像)上传到 google sheet