PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 21, 2022

[FIXED] How to make ember, rails and active_model_serializers execute one query on hasMany relationship?

 October 21, 2022     active-model-serializers, ember.js, has-many, ruby-on-rails     No comments   

Issue

I am using ember with rails and active_model_serializers.

Lets say I have a model called report and it has many statistics. Lets say one report has 2000 statistics. When I call:

report.get('statistics').then(statistics => {
  //Do something
});

I get 2000 separate api calls to statistics and 2000 separate selects from my db.

When I add include:['statistics'] to the controller method like so:

def show
  render json: @report, include:['statistics']
end

I get the same issue.

I am not sure if there is something I have to do to the ReportSerializer.rb file to enable to one query as oppose to 2000 for the comments relationship.

In a rails only application a call to my association generates one query. And while I realize ember is not rails, I figure I am missing something simple.

So, how do I make accessing the association on my model generate one api call and one query? Or at least minimize the amount of api calls and queries?

Added Info

All associated statistics are needed so an operation can be done on report.


Solution

I was unable to find a way for ember data and my rails backend to produce one query and one api call to acquire associations of a model. So I created another method in the report controller that only deals with sending the association.

def include_statistics
  render json: Report.find(params[:id]).statistics.to_json
end

And in my ember client I call the following:

$.ajax({
  type: 'GET',
  url: '/api/v1/reports/1/include_statistics'
}).then(points => {
    //Do something
});


Answered By - user2517182
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing