Reputation: 9415
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?
Upvotes: 0
Views: 489
Reputation: 198324
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, ... }
Upvotes: 1