add school and department api for option

dev_forum
p31729568 5 years ago
parent 50c7e9815e
commit b1e13758d3

@ -0,0 +1,11 @@
class DepartmentsController < ApplicationController
def for_option
render_ok(departments: Department.cached_names_data(current_school))
end
private
def current_school
@_current_school ||= School.find(params[:id])
end
end

@ -9,4 +9,8 @@ class SchoolsController < ApplicationController
render_ok(school_names: schools.pluck(:name)) render_ok(school_names: schools.pluck(:name))
end end
def for_option
render_ok(schools: School.cached_names_data)
end
end end

@ -2,4 +2,26 @@ class Department < ApplicationRecord
belongs_to :school belongs_to :school
has_many :department_members, dependent: :destroy has_many :department_members, dependent: :destroy
after_create_commit :reset_data_cache
after_update_commit :reset_data_cache
def self.cached_names_data(school)
Rails.cache.fetch(names_data_cache_key(school.id), expires_in: 7.days) do
school.departments.select(:id, :name).as_json
end
end
private
def reset_data_cache
# 清除部门名称缓存
if new_record? || name_previously_changed?
Rails.cache.delete(self.class.names_data_cache_key(school_id))
end
end
def self.names_data_cache_key(school_id)
"schools/#{school_id}/department_names_data"
end
end end

@ -1,4 +1,6 @@
class School < ApplicationRecord class School < ApplicationRecord
has_many :departments, dependent: :destroy
has_many :shixun_schools, :dependent => :destroy has_many :shixun_schools, :dependent => :destroy
has_many :shixuns, :through => :shixun_schools has_many :shixuns, :through => :shixun_schools
@ -8,6 +10,9 @@ class School < ApplicationRecord
has_many :ec_major_schools, :dependent => :destroy has_many :ec_major_schools, :dependent => :destroy
has_many :ec_majors, :through => :ec_major_schools has_many :ec_majors, :through => :ec_major_schools
after_create_commit :reset_data_cache
after_update_commit :reset_data_cache
# 学校管理员 # 学校管理员
def manager?(user) def manager?(user)
ec_school_users.exists?(user_id: user.id) ec_school_users.exists?(user_id: user.id)
@ -28,4 +33,23 @@ class School < ApplicationRecord
def manage_permission?(user) def manage_permission?(user)
manager?(user) || major_manager?(user) || course_manager?(user) manager?(user) || major_manager?(user) || course_manager?(user)
end end
def self.cached_names_data
Rails.cache.fetch(names_data_cache_key, expires_in: 7.days) do
School.select(:id, :name).as_json
end
end
private
def reset_data_cache
# 清除学校名称缓存
if new_record? || name_previously_changed?
Rails.cache.delete(self.class.names_data_cache_key)
end
end
def self.names_data_cache_key
'schools/names_data'
end
end end

@ -576,9 +576,13 @@ Rails.application.routes.draw do
resources :schools do resources :schools do
member do member do
resources :departments, only: [] do
get :for_option, on: :collection
end
end end
collection do collection do
get "school_list" get :school_list
get :for_option
end end
scope module: :ecs do scope module: :ecs do

Loading…
Cancel
Save