How to pass a variable to javascript in Rails 6 app

Viewed 1146

I have a rails 6 app that uses Full Calendar. I have the calendar set up and working correctly.

The only thing that I need to do to complete the calendar integration is add the @user.id to the url for the json feed that adds data to the calendar.

Here is my code:

javascript/fullcalendar/fullcalendar.js

import { Calendar } from "@fullcalendar/core";
import dayGridPlugin from "@fullcalendar/daygrid";

document.addEventListener('turbolinks:load', function() {
  var calendarEl = document.getElementById('calendar');

  var calendar = new Calendar(calendarEl, {
    
    plugins: [ dayGridPlugin ],

    eventSources: [
      {        
        url: "/users/<%= @user.id %>/jobs.json",
      }
    ]

  });

  calendar.render();

});

If I replace <%= @user.id %> with 3 then the calendar pulls data from a json.jbuilder file and the calendar works.

How do I pass the <%= @user.id %> to the calendar?

1 Answers

It's quite a common pattern in Rails applications to pass atrributes via data attributes.

In your view template you'd interpolate the user ID:

<div id="calendar" data-user-id="<%= @user.id %>">
</div>

And in your JavaScript you'd read the user ID via the dataset:

var calendarEl = document.getElementById('calendar');
var userId = calendarEl.dataset.userId;
Related