1

I have a javascript part in my view, that I want to modify through locals I have defined in a helper.

<script type="text/javascript">
var store = new Ext.data.JsonStore({
 url: '/admin/administration/users/grid_data.json',
 root: 'users',
 fields: [
 <%- for field in fields do -%>
 {name: '<%= field[:data_index] -%>'},
 <%- end -%>
 ]
});
</script>

This doesn't work, can you help me?

asked Aug 7, 2009 at 8:50

4 Answers 4

4

This script won't work in IE becuase of it's strict Javascript parser. The for loop in your code leaves a trailing , at the end of the array. That's not a valid Javascript syntax. The easiest way to move data from ruby into javascript is almost always to_json:

<% javascript_tag do %>
var store = new Ext.data.JsonStore({
 url: '/admin/administration/users/grid_data.json',
 root: 'users',
 fields: <%= fields.collect{|f| { :name => f[:data_index] } }.to_json %>
});
<% end %>

And you can leave out the .collect{|f| { :name => f[:data_index] } } if you use the same hash key in Ruby and Javascript. Much nicer, and much less prone to bugs.

Good luck!

answered Aug 7, 2009 at 12:03
Sign up to request clarification or add additional context in comments.

Comments

1

The problem is that you are going to have a trailing comma. You need to check the lenght of your field array and if it is the last element simply do not include the comma you currently have at the end of every name parameter.

answered Aug 7, 2009 at 8:54

Comments

0

First thing is to look at the generated code from the page source. Any syntax errors there? Is Ext library included somewhere in the head section of the HTML?

answered Aug 7, 2009 at 8:54

Comments

0

What about:

<%= (fields.collect {|field| "{name: #{field[:data_index]}}"}).join(',') %>
answered Aug 7, 2009 at 10:03

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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