Implement a jstree in a Rails application by utilizing JSON data and configuring the AJAX option to establish parent-child associations

Here is my model:

class Project < ActiveRecord::Base
    belongs_to :parent, :foreign_key => :project_id, :class_name => "Project"
    has_many :children, :dependent => :destroy, :class_name => "Project", :foreign_key => :project_id

Check out this jquery tree plugin with a JSON data example:

$(function () {
    $("#demo2").jstree({ 
        "json_data" : {
            "ajax" : {
                "url" : "/static/v.1.0pre/_docs/_json_data.json",
                "data" : function (n) { 
                    return { id : n.attr ? n.attr("id") : 0 }; 
                }
            }
        },
        "plugins" : [ "themes", "json_data" ]
});
});

The basic structure for supplying data in JSON format looks like this:

{ 
    "data" : {
        "title" : "The node title",

    // Leave out `attr` if unnecessary; the `attr` object will be passed to the jQuery `attr` function
    "attr" : { "id" : "node_identificator", "some-other-attribute" : "attribute_value" } },
    // Use `state` and `children` for NON-leaf nodes only
    "state" : "closed", // or "open", defaults to "closed"
    "children" : [ /* array of child nodes objects */ ]
}

I aim to dynamically create a jstree for a collection of projects. This collection can include children, each with their own children, and so on. My controller already responds to JSON, and I currently have code in the view to build the tree.

I have tested using this JSON data example, and it successfully generates the desired tree structure:

{
"data" : {
    "title" : "Projects",
    "attr" : { "href" : "/projects"  } }, 
    "children" : [  { 
        "data" : {
            "title" : "test",
            "attr" : { "href" : "/projects/7"  , "class" : "selected"  } }, 
            "state" : "open" ,
            "children" : [  { 
                "data" : { 
                    "title" : "test_1",
                    "attr" : { "href" : "/projects/9"  } },
                    "children" : [  ] } 
            ] } , { 
"data" : { 
    "title" : "test1",
    "attr" : { "href" : "/projects/8"  } }, 
    "children" : [  ] } 
], "state" : "open" }

I am looking for suggestions on how to automatically generate JSON data for my project collection following the schema provided above. Any ideas?

Answer №1

The original poster stated:

I managed to find a solution by utilizing the following functions:

def tree(id_node_selected)

  if id_node_selected.to_i==0             parents=[]         else
      parents=Project.find(id_node_selected).getParents         end

  children = ""         if <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="25046555574a4f404651560b04050514c51525">[email protected]</a>?            @projects.each_with_index do
   |p,i|
          children += p.to_node(id_node_selected,parents)
          if i < @projects.count-1
              children += ","
          end             end         end

  str = " {
          \"data\" : {
          \"title\" : \"Projects\",
          \"attr\" : { \"href\" : \"/projects\" "

  if id_node_selected=="0"            str += " , \"class\" : \"selected\" "
  end

  if children==""           str +=  " } }, \"children\" : [ ] } "       else            str
    +=    " } }, \"children\" : [ " + children + " ], \"state\" : \"open\" } "      end

  return str  end

def parents(array)

  if !self.parent.nil?            array << self.parent.id
      self.parent.parents(array)         end

  return array    end

 def getParents      ancestors = []

  res = self.parents(ancestors)

  return ancestors     end

 def to_node(id_node_selected,ancestors)

  str = " { \"data\" : { \"title\" : \"#{self.name}\",
          \"attr\" : { \"href\" : \"/projects/" + self.id.to_s + "\" "

  if id_node_selected==self.id.to_s           str += " , \"class\" :
    \"selected\" "            if !self.children.empty?
          str += " } }, \"state\" : \"open\" , \"children\" : [ "             else
          str +=  " } }, \"children\" : [ "           end         else            if !ancestors.empty? && ancestors.include?(self.id)
          str += " } }, \"state\" : \"open\" , \"children\" : [ "
          ancestors.delete(self.id)            else
          str +=  " } }, \"children\" : [ "           end         end

  offspring = ""         if !self.children.empty?
      self.children.each_with_index do |c,i|
          offspring += c.to_node(id_node_selected,ancestors)
          if i < self.children.count-1
              offspring += ","
          end             end         end

  str += offspring + " ] } "

  return str  end

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

Why is the $invalid field true in a different Angular view?

I have implemented some conditions to display my revision field. This involves accepting a number and setting it as a required field, so I have included validation checks for this purpose. Additionally, I have excluded this field from the 'edit' ...

I've recently delved into the world of JavaScript and am currently working on creating a calculator website. However, I'm facing some challenges in getting it to function

I created a calculator code using HTML, CSS, and JavaScript for a website. However, due to my limited experience with JavaScript coding, I encountered some issues. Currently, I have only implemented the number input part (not operations or deletion), but w ...

What is the best way to adjust the equal right padding or margin in the header for both IOS and Android using React Navigation options?

To ensure an equal gap on both sides for both IOS and Android platforms, I utilized a combination of techniques. For the right side, I achieved this using a minus margin, positive padding, and Platform. <Stack.Navigator screenOptions={{ contentSty ...

The argument was anticipated to be an array, yet it was actually a string instead - image-webpack-loader

While utilizing image-webpack-loader, I encountered the following error message: The images are imported in this manner: import icon10 from '../../assets/img/icon10.png'; ERROR in ./app/assets/img/icon10.png Module build failed (from ./node ...

Sharing data between components in React: How to pass a variable from one component to another

I have recently started working with React and I am facing an issue with passing constants from a parent component to a child component. import './App.css'; import { Display } from './Display'; import { Card } from ' ...

I am having trouble getting the hamburger menu to open on my website with Bootstrap. Can anyone help me troubleshoot this issue and find

Why isn't my navbar hamburger menu opening on smaller screens? Despite the links displaying correctly on larger screens, I am unable to get the navbar to open. I've tried various troubleshooting methods such as changing tags in the header, deleti ...

Exploring ways to repeatedly collapse rows using HTML, CSS, and JavaScript

GOAL: I want to freeze the header, freeze the first column, and be able to collapse rows multiple times. CURRENT PROGRESS: I have achieved freezing the header, first column, but can only collapse rows once. MY CODE SNIPPET: </head> <body> &l ...

Connect an HTML button to a Java activity

I am currently developing an Android app for my book and I have created an HTML page. I would like to add a button on this page that is linked to the following Java code: public class MainActivity extends Activity { @Override public void onCreate(Bundle ...

What is the best way to eliminate the " " character from a JSON file on Linux using the sed command?

I have a JSON file that contains multiple instances of "\t" characters, which are causing issues when I try to convert the JSON file to CSV. I have attempted various methods to remove these characters, including using the sed command as shown below: s ...

How can we ensure that a child directive in AngularJS shares the same data as its parent?

My child directive needs access to the same data as its parent pages. What would be the most effective method for sharing this data? Should the child directive fetch the data separately, or should the parent send it through attributes? ...

Retrieve the specified columns as per user-defined filters

Being completely new to JavaScript, I have been assigned the task at hand. The technology stack includes node.js, express, mongodb, and mongoose. Imagine that the database/collection(s) consist of 1000 rows and each row has 50 columns. Some columns may h ...

What are the steps for encountering a duplicate property error in TypeScript?

I'm currently working with typescript version 4.9.5 and I am interested in using an enum as keys for an object. Here is an example: enum TestEnum { value1 = 'value1', value2 = 'value2', } const variable: {[key in TestEnum]: nu ...

Conceal and reveal text with a simple user click

Currently, I am working on a website project that utilizes bootstrap. However, I am facing some uncertainty regarding how to effectively hide and display text: <nav class="navbar navbar-light" style="background-color: #e3f2fd;"> ...

The specified property type 'url' is not recognized on the provided 'Event' type

I came across the error message below [ts] Property type 'url' does not exist on type 'Event'. any This is the TypeScript (JavaScript) code snippet that I am using document.addEventListener("deviceready", onDeviceReady, false); ...

Can you explain the distinction in JavaScript between declaring a variable with `var a = xyz[]` versus `var a = xyz

Can someone clarify the difference between the following statements in JavaScript (or jQuery)? var a = xyz[] var a = xyz{} I tried looking it up online, but couldn't find a definitive answer. If anyone knows the difference, please enlighten me. ...

`Hamonization data hub schema was not located`

While working with MarkLogic DHF, I encountered an issue where the json validation function in my harmonization flow was unable to find the schema. The data flows smoothly throughout the rest of the process, but the validation function seems to struggle. M ...

Node.js Buffer problem: How to tackle it

Encountering an issue with buffers in Node.js The constant buffer is defined as follows: var commands = { BufferOne : new Buffer([0XCA, 0X11, 0X00, 0X00, 0X60, 0X01, 0X00, 0X01, 0X08, 0X07, 0X6D, 0X00, 0X00, 0X00, 0X00, 0 ...

Protecting against malicious input and securely handling parameters in a Rails

I am currently integrating a REST API into Rails 4.2 and I am keen on following the JSON API format. This is how my params are structured: { "data":{ "type": "articles", "id": "1", "attributes": { "title": "this is title", "descr ...

Compare and contrast two JSON responses

I'm currently facing an issue distinguishing between how to manage two different JSON responses. When there is only one element returned, the response differs from when there are two: Single result example: { "voteMap": { "SID": "2727", ...

Trigger a drop-down list in React when typing a specific character, like {{ or @, in an input field

Is there a way in React.js to display a list or dropdown when a user types a certain character like '@' or '{{ }}' in the input text area? The user should be able to select an option from this list and have it inserted into the text are ...