I am trying to write unobtrusive javascript, and I have in my view:
<%= javascript_include_tag "trend" %>
and in my trend.js.erb there is:
$(document).ready(function() {
<% @testsss.each do |t|%>
$('#<%= "t-"+t.id.to_s %>').click(function(event){
//alert("sometext");
$.ajax({type: "GET", url: "/returngraph?test=<%= t.id.to_s %>", dataType: "html",success:
function(data){ $("#chart").html(data)} });
});
<% end %>
});
But I got NoMethodError…
what I am doing wrong? @testsss is set of objects and same @testsss.each works in trend.html.erb from where I call javascript_include_tag “trend”
thank you
edit:
here is actual error:
NoMethodError in Statisticall#trend
Showing /xxxx/app/views/statisticall/trend.html.erb where line #1 raised:
undefined method `each' for nil:NilClass
(in /xxxx/app/assets/javascripts/trend.js.erb)
Extracted source (around line #1):
1: <%= javascript_include_tag "trend" %>
2: <div id="hhead">
I have controller Statisticall and action trend
I am guessing @testsss is defined in a controller.
The asset pipeline is not compiled or ever touched by action controller so… you cannot have instance variables you assign in your controllers in the pipeline.
Work arounds include @testsss.to_json and including that as a JS variable in your view
something like
then in your javascript do something like this using underscore.js
or you can render that js inside a view rather than the asset pipeline
Doing it this way gives you the advantage of having instance variables assigned in action controller in your js but the disadvantage of longer loading of your main page.
I perfer the first approach but that’s up to you?