简体   繁体   中英

Ruby on Rails | Postgres : How to find records with status (which is calculated based on has_many constraint). Please check the description

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

  1. school status is active when at least one student is in active state.
  2. school status is suspended when no active student but student record exists.
  3. school status is 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM