Martijn Kerckhaert
Martijn Kerckhaert

Reputation: 494

activerecord filter out based on foreign table

I am tryng to create a association where Vacancy has one or many schedules & possibly many matchings

Now I need to get the vacancies that are 2 weeks before starting and that have no matching with state approved

Vacancy.includes(:schedules)
.where(schedules: {start_date: Date.today..Date.today+14})
.order("schedules.start_date ASC")
.includes(:matchings).where.not(matchings: {state: "approved"})

The first part works fine, I'm getting my vacancies and ordering them succesfully, although afterwards filtering out the ones that have a matching with approved does not work.

Upvotes: 1

Views: 92

Answers (2)

MZaragoza
MZaragoza

Reputation: 10111

You should be able to do something like this

Vacancy.includes(:schedules, :matchings)
.where(schedules: {start_date: Date.today..Date.today+14})
.order("schedules.start_date ASC")
.where.not(matchings: {state: "approved"})

its just the order of operations that you have a problem with

I took my own project to write this Relationship

Client.includes(:documents, :equipments).where(documents: {doc_type: 'equipment'} ).where(equipment: {shipper_id: 24}).count # 4

Client.includes(:documents, :equipments).where(documents: {doc_type: 'equipment'} ).where.not(equipment: {shipper_id: 24}).count # 314

Upvotes: 1

Aniket Rao
Aniket Rao

Reputation: 778

May be you could try this?

Vacancy.joins(:schedules,:matchings).where(schedules: {start_date: Date.today..Date.today+14}).order("schedules.start_date ASC").where.not(matchings: {state: "approved"})

Upvotes: 1

Related Questions