3

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?

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That's my case too, but I want to have the same JS in multiple views (not everywhere). When I put my JS in an external file, the ERB doesn't evaluate. Any ideas?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.