0

I'm trying to access some ruby instance variables through a coffeescript file. At what point do instance variables become defined? For example, when I try the following:

$(window).load () ->    
 $('#s3-uploader').S3Uploader
    additional_data: {project_id: <%= @project.id %>, step_id: <%= @step.id %>, user_id: <%= current_user.id %>} 

I get the error

Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id
  (in /images.js.coffee.erb)

I know that @project should be defined, though, since I use it on the page when it's loaded. What am I doing wrong?

1 Answer 1

1

Your CoffeeScript and your page are most likely in different views. Thus, having @project available when rendering your page says nothing about its availability when you're rendering your JavaScript. The easiest way to transfer this is to define a JavaScript variable inside your page view. For instance, if you're using Haml or Slim:

coffeescript:
  window.MyModule.project_id = #{ @project.id }

and then change your code to

additional_data: { project_id: window.MyModule.project_id, ... }
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your advice. If my page is loaded via a partial, how would I define the project_id variable? Would it be something like <script>window.MyModule.project_id = <%[email protected]%></script> ?
Doesn't matter if it's partial or not, but what engine you're using. If you're using ERb (as it seems), then yes. Given that you're writing in regular JavaScript and not CoffeeScript, a semicolon would be advisable (even though unnecessary) as good JS style.

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.