【问题标题】:Find records based on its other parent child根据其他父子项查找记录
【发布时间】:2018-10-05 17:45:29
【问题描述】:

我有这样的关联:

class Ship < ApplicationRecord
 has_many :captain_profiles
 has_many :captains, through: :captain_profiles
end

class CaptainProfile < ApplicationRecord
  belongs_to :captain
  belongs_to :ship
end

class Captain < ApplicationRecord 
  has_one :captain_profile
  has_many :schedules
end

class Schedule < ApplicationRecord
  belongs_to :captain
end

而且我需要准备好出海的所有船只的清单。换句话说,我必须找到所有至少有一名船长的船,并且至少有一个船长。

我考虑合并两个内部连接,因为我需要具有船长和附表的船舶。 我尝试了Captain.includes(:schedules).where("schedule.id IS NOT NULL") 和 Ships,但它不起作用。有人可以解释一下我做错了什么,我该怎么做?

【问题讨论】:

    标签: ruby-on-rails postgresql rails-activerecord


    【解决方案1】:

    只需使用生成INNER JOINjoins

    Ship.joins(captains: :schedules)
    

    【讨论】:

      猜你喜欢
      • 2022-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-07
      相关资源
      最近更新 更多