How to assign a Rails controller value to a JavaScript constant

371 views Asked by At

I have a constant within a JavaScript function that needs to take a value from a Rails controller or directly from a JSON endpoint.

Here is the controller action that returns the value that I need:

class EventsController < ApplicationController

def calendar
    client = Signet::OAuth2::Client.new(client_options)
    client.update!(session[:authorization])
    service = Google::Apis::CalendarV3::CalendarService.new
    service.authorization = client

  @calendar_list = service.list_calendar_lists.items

  rescue Google::Apis::AuthorizationError
    response = client.refresh!
    session[:authorization] = session[:authorization].merge(response)
    retry
  end

This controller action has a corresponding JSON endpoint as well, localhost:3000/calendar.json:

This JavaScript is in my application.rb file. I tried passing my calendarList constant the instance variable @calendar_list but that didn't work.

function getEventSources(){
  const calendarList = <%= @calendar_list %>
  const keyArray = calendarList.map(cal => {
  return 'googleCalendarId'
  })

  const calendarIds = calendarList.map(cal => {
  return cal["id"]
  })

  eventSources = []

  for(i=0; i < keyArray.length; i++) {
    var obj = {}
    obj[keyArray[i]] = calendarIds[i]
    eventSources.push(obj);
  }
return eventSources
};

This is my /calendar.json endpoint:

[
  {
    id: "en.usa#[email protected]",
    summary: "Holidays in United States"
  },
  {
    id: "nba_1_%41tlanta+%48awks#[email protected]",
    summary: "Atlanta Hawks"
  }
]

Do I need to make some type of AJAX call to retrieve this value or is there a simpler way?

2

There are 2 answers

0
kel.o On BEST ANSWER

I moved my javascript into a html.erb file and out of application.js

This is how I passed the controller value to my JavaScript constant

const calendarList = <%= raw @event_list %>

this did the trick.

4
refrigerizer On

I believe you either have to surround the embedded Rails variable in single quotes, like

'<%= @calendar_list %>'

or, if the variable contains an array of objects, which I'm assuming it does since it's described as a list, you have to have JavaScript parse it as a JSON object.

Basically the data from Rails isn't in a format that JavaScript knows how to interpret so you need to format it as a string or object so JavaScript can read it.