Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get records based on other table

I'm very new to Ruby and have no idea to do this. I need to create a select based on 2 tables: A and B. Both are ActiveRecord.

class A < ActiveRecord::Base
  belongs_to :b
end

class B < ActiveRecord::Base
  has_one :a
end

There are A records with no B records associated. I would like to get those records with this problem.

like image 766
learner Avatar asked Feb 19 '26 23:02

learner


2 Answers

Yet another option is to use includes:

A.includes(:b).where(bs: { id: nil })

It will make a single query to database.

like image 164
Andrey Deineko Avatar answered Feb 21 '26 11:02

Andrey Deineko


You can retrieve A records with a B record associated with:

A.joins(:B)

if you need all A records which don't have an association with B you can execute:

A.where(B: nil)
like image 42
coorasse Avatar answered Feb 21 '26 11:02

coorasse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!