Exploring the World of Dynamic Table ID Access in Rails 5 with Coffeescript

Within my Index view, I have a table that I want to dynamically populate with an ID. This is what I've attempted so far:

id="table_<%= @controller_name %>"

The method in my controller looks like this:

def get_controller_name
  @controller_name = self.class.name.split("::").last
end

Next, I need to access a specific table in my Coffeescript. Here's how I've done it:

$ ->
  myvar = '<%= raw @controller_name.to_json %>'
  myvarAsObj = JSON.parse(myvar)
  $('#' + 'table_' + myvarAsObj).DataTable

However, it doesn't seem to be working as expected. When I check the Page Source, the Table ID appears as follows: id="table_MyController"

Could you please advise on the correct way to access the table ID in Coffeescript? Thank you!

Update:

This is the table in my Index:

<table data-controller-name="<%= @controller_name %>" cellpadding="0" cellspacing="0" 
border="0" class="table table-striped table-bordered table-hover" width="100%" 
data-source="<%= campaign_campaigns_index_path(format: :json) %>">

Here's the Coffeescript code:

$ ->
  $('table[data-controller-name]').each ->
    $(this).DataTable
    ajax: $('table[data-controller-name]').each ->
      $(this).data('source')

When I look at the Page Source, I see the following:

<table data-controller-name="CampaignsController" cellpadding="0" cellspacing="0" border="0"
  class="table table-striped table-bordered table-hover" width="100%"
  data-source="/en/campaigns.json">

Answer №1

It seems that the <%= raw ...%> in your coffeescript is being taken literally. To avoid this issue, consider passing data from Rails to Coffeescript through HTML data attributes instead of trying to interpolate it directly. Utilizing data-attributes can help reduce coupling between your Rails and Javascript code.

One way to achieve this is by following these steps:

ApplicationController.rb

def get_controller_name
  @controller_name = self.class.name.split("::").last
end

CampaignsController.rb

def index
  # Render your data as JSON. For example:
  render json: {
      data: [
        [
          "Tiger Nixon", "System Architect", "Edinburgh", "5421", "2011/04/25", "$3,120"
        ],
        [
          "Garrett Winters", "Director", "Edinburgh", "8422", "2011/07/25", "$5,300"
        ]
      ]
    }
end

home.coffee

$ ->
  $('table[data-controller-name]').each ->
    el = $(this)

    el.DataTable {
      ajax: el.data('source')
    }

index.html.erb

<table data-controller-name="<%= controller.get_controller_name %>"
       data-source="<%= campaign_campaigns_index_path(format: 'json') %>">
   <thead>
     <tr>
         <th>Column 1</th>
         <th>Column 2</th>
     </tr>
   </thead>
   <tbody>
       <tr>
           <td>Row 1 Data 1</td>
           <td>Row 1 Data 2</td>
       </tr>
       <tr>
           <td>Row 2 Data 1</td>
           <td>Row 2 Data 2</td>
       </tr>
   </tbody>
</table>

The coffeescript provided will target any tables with a data-controller-name attribute attached to them.


Update: To include ERB tags within Coffeescript, you can simply append .erb to the Coffeescript filename like so:

home.coffee.erb

$ ->
  $('#table_<%= @controller_name %>').DataTable {
    ajax: el.data('source')
  }

Nevertheless, I recommend utilizing the HTML data-attributes method mentioned above for its enhanced flexibility and separation of Coffee/Javascript from the Rails logic.

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

Unique hover tags such as those provided by Thinglink

Looking for a way to replicate the functionality of Thinglink? Imagine a dot on an image that, when hovered over, displays a text box - that's what I'm trying to achieve. I thought about using tooltips in Bootstrap, but I'm not sure if it ...

Using a JavaScript class rather than an ID for toggling visibility

As a complete newbie to JavaScript, I've come across similar questions but I'm lost when it comes to coding - help needed! So here's the code I have so far, and I'm hoping someone can assist me. Currently, I have JavaScript set up to s ...

The access to the HTTP response object is not possible: the property is not found on the Object type

I recently created a response object and assigned it to the "this" object. However, when I try to access the datacentersinfo property, I encounter an error stating that the property does not exist on type Object. Due to this issue, I am unable to generat ...

Filter numbers within an Array using a Function Parameter

I'm currently experimenting with Arrays and the .filter() function. My goal is to filter between specified parameters in a function to achieve the desired output. However, I'm encountering an issue where my NPM test is failing. Although the outpu ...

Selecting dates based on week number

Is there a method in asp.net or via javascript to capture the dates (Monday to Friday) when a user clicks on the week number displayed on the calendar and display them on a label? ...

The command 'var' is not recognized as an internal or external command within npm

I need assistance with installing the histogramjs package. The command npm i histogramjs successfully installs it, but when I attempt to run the code using var hist = require('histogramjs'), I encounter an error in the command prompt: 'var& ...

One might encounter undefined JSON keys when attempting to access them from a script tag

During my attempts to load a specific Json using an Ajax GET request and then parsing it, I encountered an issue when trying to access the Json key from an HTML script tag, as it returned as undefined. To troubleshoot this problem, I decided to log all th ...

How can you identify the specific HTML page that a jQuery selector is targeting?

In an attempt to create jQuery code that counts the number of <img> elements on a website, I encountered a unique challenge. The website consists of 4 separate HTML pages stored in the same folder on the server. Among these pages, only "pics.html" is ...

In my Vue watch method, I have two parameters specified, and one of them remains constant without any changes

Currently, I am attempting to access a method within my watch function with two parameters. Here is the code snippet for the method: onBoolianChange(value, willChange) { willChange = (value === false) ? true : false; }, watch: { "e ...

The x-axis is represented by JSON keys, while the y-axis is represented by

I am currently attempting to replicate a graph that was originally made in Excel. Here is the code I have written so far: var data = [ { 'FB':4, 'Mv':4, 'CB':5, 'SL':3, ...

Ensure that only the dropdown menu that is clicked within a Vue loop opens

Hey, I'm having an issue with my dynamically created drop-down menus. I can display them correctly using v-Show, but the problem is that when I click on one element, they all open below my code. <div :class="{inizio : utenteAttivo.nome === con ...

I am attempting to implement an Express static middleware as demonstrated in this book, but I am having trouble understanding the intended purpose of the example

I'm currently studying a chapter in this book that talks about Express, specifically concerning the use of express.static to serve files. However, I'm encountering an issue where the code catches an error when no file is found. I've created ...

retrieving JSON data within the controller

When I use the command console.log($scope.data), I am able to view my JSON file. Additionally, by using <div ng-repeat="item in data">, I can see all the items in the view. However, when I try console.log($scope.data[0]) or console.log($scope.data[0] ...

Ways to position loading animation in the center and create a lightbox effect for the rest of the page

I have implemented a custom loader in CSS with the following styles: .loader { border: 16px solid #f3f3f3; /* Light grey */ border-top: 16px solid #3498db; /* Blue */ border-radius: 50%; width: 80px; height: 80px; animation: spin 2s linear inf ...

Master the Art of Scrollbar Control in Angular!

I am currently developing a chat web application that functions similar to gchat. One of the key features I'm trying to implement is an alert notification when the scrollbar is in the middle of the div, indicating a new message. If the scrollbar is at ...

Failed to cast value "undefined" to ObjectId in the "_id" path for the model "User"

I've been encountering an issue that I can't seem to resolve despite searching on Stack and Google. My ProfileScreen.js is meant to display a user's profile, but when attempting to view the profile, I receive this error: "Cast to ObjectId fa ...

Error: Authentication error. fatal: Unable to access the remote repository." encountered while executing the command "yarn install

Today, while developing a web application, I encountered an issue with the "yarn install" command. Upon running "yarn install", the console displayed an error message: "Host key verification failed. fatal: Could not read from remote repository." I attemp ...

The unrevealed node that is requesting the module is leading to an undefined outcome

I'm facing an issue where I need to import var server = require('../../index.js'); in my foo-dao.js file. This is necessary for accessing a hapi server plugin without passing it through the hapi request object from controller to dao. The pr ...

Mapping memory for FirefoxOS is like equivalent strides

Is there a way to create a memory mapped file in FirefoxOS, Tizen or other pure-JS mobile solutions? In the scenario of a mobile browser where you have large amounts of data that can't fit in RAM or you prefer not to load it all at once to conserve R ...

Inserting an item into a list

Looking for assistance with this particular scenario: { "EekvB3cnwEzE":{ "name":"hi", }, "Brv1R4C6bZnD":{ "name":"yup", }, "kRwRXju6ALJZ":{ "name":"okay", } } I'm attempting to store each of these objects in an array. Howe ...