Ben Poon
Ben Poon

Reputation: 125

Pass instance variable to js Rails

In my search controller I have an instance variable, @results. I set it to return a dummy result, 'foo'.

In my search.html.erb view... I set window.results = <%= raw @results.to_json %>.

At the top of my search.js asset file, I console.log(results) and get undefined, but when I get into the devtools after the page load, results is populated with 'foo'. The console.log statement is also wrapped in a jquery ready function.

What gives?

Upvotes: 3

Views: 1307

Answers (1)

Steve
Steve

Reputation: 4566

Rails assets are precompiled so they don't have access to instance variables coming from the controller. Embed the Javascript directly into your view using a script tag and access the @results just like you did. You could also initiate a call to an external Javascript file.

Upvotes: 4

Related Questions