Issues encountered with Rails server due to excessive JavaScript calls causing crashes

I have been working on developing a dynamic reporting feature as part of a larger project. The specific issue I am facing is that the functionality works fine for multiple calls but eventually leads to a server crash. I am utilizing mongoid and puma server - please feel free to ask if you need more details.

Despite extensive research, I have hit a wall with this problem. Any help would be greatly appreciated!

Error Message in Console The error message displayed here is just the beginning, with additional details provided in subsequent pages such as "Control frame information", "Other runtime information", and the "Process memory map"

/usr/local/rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/forwardable.rb:228: [BUG] Segmentation fault at 0x00000000000038
ruby 2.4.0p0 (2016-12-24 revision 57164) [x86_64-linux]

Important JavaScript Code Segment This script stores the category field value and adds all selected column values (from a multiselect form) to an array. Subsequently, both variables are sent to the get_filter_columns controller action.

<script>
    $(document).ready(function(){
        function get_filter_columns(filter_columns, category){
          $.get('reports/get_filter_columns',{filter_columns, category});
        };

        $(document).on('change', "#filter_columns", function() {
            var filter_column_array = [];
            var category = $("#report_category").val();
            $("#filter_columns .box2 option").each(function() {

                filter_column_array.push($(this).val());
            });
            get_filter_columns(filter_column_array, category);
        });  
   });
</script>

_filter_columns.html.erb This code snippet represents an element in the view that responds to the onchange event in JavaScript.

<div id = "filter_columns" class="col-lg-5">
    <div class = "ibox-content report_builder_body">
        <h2>Filter Columns</h2>
        <%= simple_fields_for :filter_columns_nested_form do |ff| %>
            <%= ff.select( :filter_columns, (@category || Account).attribute_names.map{ |value| [value.to_s.underscore.humanize, value] }, {}, { :id => "filter_columns", :class => "form-control dual_select_filter_columns", :multiple => true })  %>
        <% end %>
    </div>
</div>

reports_controller.rb This is the controller action invoked by the JavaScript code.

    def get_filter_columns

        @category = (params[:category] || "Account").split(' ').collect(&:capitalize).join.constantize

        @filter_categories = (params[:filter_columns] || []).map{ |filter| filter }

        @filter_symbols = {}

        @filter_logic = ["Equal to", "Not equal to", "Less than", "Less than or equal to", "Greater than", "Greater than or equal to", "Is between", "Is not between"]

        @filter_categories.each do |fs|
          if @category.instance_methods(false).include?(fs.to_s.to_sym) == true
            @filter_symbols[fs] = "enum"
          elsif @category.pluck(fs.to_s.to_sym)[0].class.to_s == "BSON::ObjectId"
            @filter_symbols[fs] = "string"
          elsif @category.pluck(fs.to_s.to_sym)[0].class.to_s == "NilClass"
            @filter_symbols[fs] = "string"
          elsif @category.pluck(fs.to_s.to_sym)[0].class.to_s == "Time"
            @filter_symbols[fs] = "date"
          else
            @filter_symbols[fs] = @category.pluck(fs.to_s.to_sym)[0].class.to_s || "string"
          end
        end

        render "reports/js_templates/get_filter_columns.js.erb"
    end

get_filter_columns.js.erb This file contains the JavaScript template that is rendered by the get_filter_columns controller action.

$('#filters').replaceWith('<%= j render("reports/partials/filters") %>');

_filters.html.erb This partial is being rendered by the get_filter_columns.js.erb file.

<div class="col-lg-7" id = "filters">
    <div class = "ibox-content report_builder_body">
        <h2>Filter Criteria</h2>
        <div class="scroll_content">
            <% if @filter_categories.nil? || @filter_categories.size == 0 %>
                <p> No filter columns have been selected! </p>
            <% else %>
                <%= simple_fields_for :filters_nested_form do |ff| %>
                    <% (@filter_categories || []).each do |filter| %>
                        <div class = "col-lg-3"> 
                            <h5>
                                <%= filter.to_s.underscore.humanize %>:
                            </h5>    
                        </div>
                        <%= ff.simple_fields_for :"#{filter}" do |fff| %>
                            <div class = "col-lg-5">
                                <%= fff.input :logic, collection: @filter_logic, label: false %>
                            </div> 
                            <div class = "col-lg-4">
                                <%= fff.input :criteria, as: :"#{@filter_symbols[filter].to_s.downcase}", label: false %>
                            </div>   
                        <% end %>    
                    <% end %>
                <% end %>
            <% end %>
        </div>
    </div>    
</div>

Answer №1

If you're encountering an error, consider making this adjustment in the controller code to reduce unnecessary database queries. By implementing this change, you can avoid multiple DB hits when using pluck repeatedly.

ClassOverrideList = {
  "BSON::ObjectId" => "string",
  "NilClass" => "string",
  "Time" => "date"          
}

def get_filter_columns

    @category = (params[:category] || "Account").split(' ').collect(&:capitalize).join.constantize

    @filter_categories = (params[:filter_columns] || []).map{ |filter| filter }

    @filter_symbols = {}

    @filter_logic = ["Equal to", "Not equal to", "Less than", "Less than or equal to", "Greater than", "Greater than or equal to", "Is between", "Is not between"]

    @filter_categories.each do |fs|
      fs_sym = fs.to_s.to_sym
      if @category.instance_methods(false).include?(fs.to_s.to_sym) == true
        @filter_symbols[fs] = "enum"
      else
        category_class = @category.pluck(fs_sym)[0].class.to_s
        @filter_symbols[fs] = ClassOverrideList[category_class] ||
          category_class ||
          "string"
      end
    end

    render "reports/js_templates/get_filter_columns.js.erb"

Answer №2

The issue was traced back to a series of calls to the .class and .instance_methods methods in quick succession using JavaScript. By removing these method calls from the controller action, I was able to resolve the problem completely.

To fix the issue, I took a different approach by generating a nested hash during the initial page load (see example format below). This hash is then sent back to the get_filter_columns controller action to prevent the need for recreating the hash and calling the problematic methods within the controller again.

column_symbols = { model_1_name: { column_1_name: data_type, column_2_name: data_type }, model_2_name: { column_1_name: data_type, column_2_name: data_type }..... } 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieving data from MongoDB GridFS into a Spark 2.x DataFrame using Python

I am exploring the possibilities of using pyspark sql with keras through elephas. One interesting idea I have is to experiment with distributed image processing using mongoDB GridFS. While I did come across a similar question in the Java world regarding ...

What are some methods for preventing JavaScript function calls from the browser console?

In the process of developing a web application using HTML and JavaScript, I'm looking for a way to prevent users from accessing functions through their browser console in order to maintain fairness and avoid cheating. The functions I want to protect a ...

Unable to find the module... designated for one of my packages

Within my codebase, I am utilizing a specific NPM package called my-dependency-package, which contains the module lib/utils/list-utils. Moreover, I have another package named my-package that relies on my-dependency-package. When attempting to build the pr ...

What information is displayed on the visible class roster?

I'm feeling a bit lost with this. element.classList.add('visible'); Can someone clarify what the 'visible' in this code snippet is? Is it an event or something else? Appreciate your help! ...

Invoking a .js file within an UpdatePanel from the CodeBehind

I have been dedicating my time to self-teach ASP.NET and JavaScript for a project, and I've hit a roadblock that has consumed dozens of hours. After discovering a fantastic drag-and-drop JavaScript list online, I copied the provided source code and o ...

Menu options submerged beneath the surface of a concealed container with overflow property

Attempting to enhance the ui-grid by adding more options to each row using the "3 dots" approach. However, encountered an issue where the dropdown menu extends beyond the screen due to the use of position: absolute. Unable to switch to position: relative b ...

What is the best way to find the product of each object in an array by the corresponding values in another array?

Searching for a solution to an issue I encountered while working on an assignment. The problem can be illustrated as follows: var arrOfObj = [{a:10 },{a:20},{a:30}, ......] var arrToMultiply = [2,4,6, .....] The expected result const result = [{a:10,resul ...

Issue with AJAX MVC HTML: jQuery value is not blocking API call

Upon clicking a button, I am triggering a web API call using AJAX. My form is utilizing JqueryVal for form validations based on my viewmodel data annotations. The issue I am facing is that when I click the "Listo" button in my form, it executes the API ca ...

I'm a complete programming newbie and I want to start learning JavaScript, jQuery, and other programming languages. Where should I

Coming from a design background with zero programming knowledge, I have recently learned XHTML and CSS. Now, I am eager to expand my skills by mastering JavaScript, jQuery, and more. Where should I begin? This will be my first foray into programming. Whil ...

What is the best way to obtain the value of a radio button using ajax?

Here is the search button in my PHP file. I am unsure of how to connect the radio button to the JavaScript file. <button id="submit">Search</button> This is the starting point in the JavaScript file var xhr = new XMLHttpRequest(); f ...

vuex: The decision between using $store.commit and directly calling the function

Recently, I discovered an interesting technique where store mutation functions can be passed into HTML events. Here's an example: //In the template <input name="the_field" :value="the_field" @input="updateField"/> // In the component methods ...

Attempting to alter the background image through the action of clicking on an image using jQuery, HTML, and CSS

I have created custom weather icons like a sun, cloud, and rainy cloud using Photoshop. My goal is to allow users to click on these icons and change the background image of the website's body. However, despite my efforts, clicking on the images does n ...

Transform a span into a div while retaining its content and styles, ensuring compatibility with Internet Explorer

Is there a reliable JavaScript method to convert a span into a div while preserving its contents and the original classes of the span? The classes are pre-set, so hardcoding should be possible. <span class="my class"> <p class="conten ...

Adding or editing an item within a nested array that has been converted to a string in a mongoDB document

My data set is organized in the following format: { "_id" : "7ZEc8dkbs4tLwhW24", "title" : "title", "json" : { \"cells\":[ { \"type\":\"model\", ...

Transform this color matching game into an image matching game using JavaScript and jQuery

I have a color matching game that I would like to enhance by matching background-images instead of just background-colors. However, I am facing difficulties in making this change. For instance, instead of matching the color red with the text "red," I wan ...

The Vue router-view is not showing certain views as expected

Apologies for the extensive text. All of my router-views are functioning properly, except for one specific view which appears blank. Despite meticulously reviewing the code multiple times, I cannot identify any errors or warnings in the console. The struct ...

The VueJS dynamic grid view

Currently, I am working on a project in VueJS using vue cli 3. I am facing an issue with implementing MasonryJS into my Vue project. The challenge lies in grasping how to integrate this masonry layout into my Vue application. ; (function(window) { // J ...

Having Difficulty with Splicing Arrays in React?

Currently working on learning React and trying to develop my own mini-app. I'm basing it very closely on the project showcased in this video tutorial. I've run into an issue with the comment deletion functionality in my app. Despite searching va ...

What are the implications of a project containing nested node_modules directories?

We are currently in the process of dividing our project into "sub modules" within a single repository. Our goal is to maintain aspects such as webpack configurations and express server globally, with a structure similar to the following: package.json serv ...

The ng-repeat directive fails to acknowledge changes in the model

I'm having trouble iterating over the properties of a model that I am updating. Below is the code snippet from my controller: app.controller('VariantsController', ['$http', function($http){ var ctrl = this; this.cars = []; ...