Imagine this scenario: I have a view named "Dashboard" featuring a basic form and a button labeled "Draw Graphs". The goal is to trigger two ajax requests upon clicking the button, fetching the required data from the database for creating two distinct graphs. The catch is that both requests should avoid redundancy by utilizing the same query.
Currently, my approach involves firing a single ajax request when the button is clicked, querying mysql for the necessary data. This retrieved data is then passed as parameters to two additional ajax requests in order to structure the graphs using javascript.
This process can be outlined as follows:
JavaScript:
$('#draw_graphs').click(function() {
$.ajax({
url: 'single_query',
dataType: 'json',
data: $('#myForm').serialize(),
method: 'get'
}).success(function(activeRecord) {
ajax_graph1(activeRecord);
ajax_graph2(activeRecord);
});
});
ajax_graph1 = function(activeRecord) {
$.ajax({
url: 'create_g1',
dataType: 'json',
data: {active_record: active_Record},
method: 'post'
}).success(function(g1) {
create_g1(g1);
});
};
ajax_graph2 = function(activeRecord) {
$.ajax({
url: 'create_g2',
dataType: 'json',
data: {active_record: active_Record},
method: 'post'
}).success(function(g2) {
create_g2(g2);
});
};
Rails:
def single_query
result = Data.where("etc... etc...")
respond_to do |format|
format.json { render json: result.to_json }
end
end
def create_g1
activerecord = params[:active_record]
graph1 = {}
activerecord.each do |ar|
#do whatever with graph1
end
respond_to do |format|
format.json { render json: graph1.to_json }
end
end
def create_g2
activerecord = params[:active_record]
graph2 = {}
activerecord.each do |ar|
#do whatever with graph2
end
respond_to do |format|
format.json { render json: graph1.to_json }
end
end
The issue arises when attempting to pass an active record from the controller to javascript and back to the controller again. It appears that the structure gets altered in the process. While single_query
's result
belongs to ActiveRecord_Relation
class, it transforms into ActionController::Parameters
class while passing through the "javascript layer."