I have a listing page of schools where I have to list the name and status of the school. The status is calculated based on the student's status.
Here is my models...
class School < ActiveRecord::Base
has_many :students
has_many :teachers
end
class Student < ActiveRecord::Base
belongs_to :school
enum status: {
active: 'active',
suspended: 'suspended'
}
end
So, the idea is list the school name and school status as
active
when at least one student is in active
state.suspended
when no active student but student record exists.closed
when there is no students record against school. I am trying hard to find the query to get the data like I wanted. Since this is a has_many
I am finding it difficult for me. I use postgresql database.
Any help will be appreciated.
Note: I need the sql query to find this. (something like combining two tables, calculating the status based on the condition)
You can iterate over schools and count by statuses with @school.students.group(:status).count
. It will return an ordered hash mapping statuses with their count.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.