Reputation: 751
Given the models below:
class Score < ApplicationRecord
belongs_to :composition
end
class Composition < ApplicationRecord
has_many :scores
has_one :invoice, dependent: :destroy
end
class Invoice < ApplicationRecord
belongs_to :composition
end
what's the best way to find the scores, whose composition has a nil
invoice?
I tried:
Score.joins(:composition).where(composition: {invoice: nil})
csn = Composition.includes(:invoice).where(invoices:{id:nil})
Score.where(csn.include? composition)
Score.where(csn.map(&:id).include? composition_id)
Score.where(Composition.left_outer_joins(:invoice).where(invoices:{id:nil}).includes? composition)
all with errors. Any ideas?
EDIT: here are the corresponding tables as per schema.rb
:
create_table "compositions", force: :cascade do |t|
...
end
create_table "invoices", force: :cascade do |t|
t.integer "composition_id"
...
t.index ["composition_id"], name: "index_invoices_on_composition_id", using: :btree
end
create_table "scores", force: :cascade do |t|
t.integer "composition_id", null: false
...
end
Upvotes: 3
Views: 125
Reputation: 2004
Please try following query,
Score.joins(:composition).where('compositions.id NOT IN (?)', Invoice.pluck(:composition_id))
If this not work then let me know the columns present in compositions
and scores
tables
Upvotes: 0
Reputation: 1254
Please try following query:
Score.joins(:composition).includes(composition: : invoice).where(invoices: { id: nil })
Upvotes: 1
Reputation:
Try following
Score.joins(:composition).where('compositions.invoice_id IS NULL')
above should work, Have a good luck!!!
Upvotes: 0