i'm having performance issues because rendering json object on 1000 rails objects. happening small amount of users have access of data. > 5%.
i have 3 types of objects nested json. regions, districts, , schools. region has_many districts , schools. district has_many schools.
there 7 regions, 85 districts, , 3000+ schools.
these loaded select fields , switched depending on region or district chosen.
my first solution render regions , districts json , populate selects necessary. use ajax school objects belong chosen district when needed. caused performance issues districts have hundreds of schools. , every time user switched district or region, have call ajax hundreds of schools, causing page freeze up.
my recent solution render right on page load. makes page operate no lag, > 5% of users takes around 7 seconds query json!
i'm not sure how speed process up, current code handle putting data need json.
to render json, call:
user.grantable_regions.to_json
user.rb:
def grantable_regions if has_role?(:developer, :staff, :state_user) region.all else # regional-level permissions regions = [] self.permissions.region_permissions.can_grant.uniq.each |perm| regions << region.find_by(id: perm.region_id) end regions end end region.rb:
def as_json(opts) super(only: [:id, :name], methods: :active_districts) end def active_districts districts.active end district.rb:
def as_json(opts = {}) super(only: [:id, :name], include: { schools: { only: [:id, :name] } } ) end school.rb
def as_json(options={}) { :id => id, :name => name } end example json:
{\"id\":1,\"name\":\"region 1\",\"active_districts\":[{\"id\":3,\"name\":\"foo\",\"schools\":[{\"id\":118,\"name\":\"foo high school\"}]}] does have ideas on how can speed up? again happens > 5% of users.
as strategy, i'd recommend not loading data front. load top level options, when user makes top-level choice, ajax-load in data below choice, etc etc.
so, choose region, ajax load districts in region, choose district, ajax load schools in district.
this way, split process series of small queries rather 1 huge monolithic one. benefit performance in lots of different ways.
just noticed tried already: think gave easily! if it's freezing trying load 100 school's data don't see how loading of schools on entire system going make things better! instead, @ slowing ajax load of schools within district. might can improve db performance adding indexes, or maybe code using data unecessarily complicated or slow.
also, ajax-loading, @ how user selects school. looking single school? if so, keyword search better showing schools in select: it's easier user , it's more efficient.
Comments
Post a Comment