Using .js.erb with Webpacker and instance variables Rails parsing not working

Viewed 13

I'm trying to render my Active record JSON in a webpacker JS file:

My controller:

@products = Product.all
respond_to do |format|
    format.html {  render 'new'}
    format.json
    format.js
end

In my js.erb file that I want to compile

var products = JSON.parse('<%= j @products.to_json.html_safe %>')

Once Webpacker compiles it, the following error shows:

Unexpected end of JSON input

View Output (json will be empty and not parsed):

var products = JSON.parse('');

How can I pass instance variables with JSON from my controller to a webpacker JS file? This is driving me nuts!

Thanks in advance

0 Answers
Related