The core unit of your system is the School_Class, right? I’m trying to think of why you would need to know that a student has zero teachers vs needing to know that he is in zero classes.
Hi @pdbradley , I’m still working on this. I should tell you there are a few complications that have stumped me along the way:
Every student has a private class by default (for one-to-one learning) and that private class can have many teachers. Students can also belong to group classes, which can also be taught my multiple teachers. So I can’t just look for student’s without any class memberships. I could look for students in only one class and check that class is a private one but that seems equally complicated.
Teacher is inherited from the main Devise user model. Not sure if this is a complication, just mentioning for clarity.
The app is multi-tenanted using default_scope and a school_id. This makes working with queries in the console umm… challenging.
The only working solution I have is this:
Student.all.select {|s| s.teachers.length == 0 }
but as you can tell, that queries the teacher count for every student which is quite a performance hit.
Each school only has hundreds of students, not thousands or hundreds of thousands, so it may be feasible to use this but it does smell quite bad.
Dan, what about this, in the second it block. Try it and see if it works. This test passes for me.
Basically if you include the farthest association, the query will contain a series of left outer joins, and you can pick an associated column in one of the joined tables; if it is nil, then the table contains no records in the join and so your originating model is “orphaned” in the sense of having no associated records.
So by finding records (Students) for which the teacher_id in timeslot is nil, you are finding Students without any teachers. Clunky but maybe it is enough. Here is the repo:
where you can see I was trying to work with timeslots to get what I want, but you nailed it!
You solution works perfectly. Thanks so much for putting your time into this. This not only solved my current problem but has armed me with the knowledge to solve future problems like this myself.
Which gives the same result. that way you are checking for the existence of a column on the teachers table and it is a little bit clearer what you are doing.
ActiveRecord::StatementInvalid:
PG::UndefinedTable: ERROR: missing FROM-clause entry for table "teachers"
LINE 1: ...acher_id" AND "users"."type" IN ('Teacher') WHERE "teachers"...
That’s actually one of the first things I tried and got stumped when it wouldn’t let me reference teachers in the query.
I can’t figure out how to include teachers as users. I read the APIDock page but includes doesn’t seem to have options like as:.
Any ideas? I’m fine with the slightly longer timeslots solution but I’d still like to know how to reference an STI model like this in a query.