nanakondor
nanakondor

Reputation: 745

Ruby/Rails find record that has no association

I have these models: Table1 and Table2. Table1 has_many Table2, Table2 belongs to Table1. How can I find a Table1 record that doesn't have associations to Table2? Something like:

Table1.where(table2_relations.empty?)

Upvotes: 1

Views: 23

Answers (1)

Keith Pitty
Keith Pitty

Reputation: 1508

Let me use a more real-world example. Say we have the following classes:

class Order < ApplicationRecord
  has_many :products
end

class Product < ApplicationRecord
  belongs_to :order
end

Then you could do the following:

Order.all.select { |order| order.products.empty? }

I hope that helps.

Upvotes: 1

Related Questions