Forum: Ruby on Rails passing rails data to javascript

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Jorge Mario G. Mazo (Guest)
on 2007-03-09 08:57
(Received via mailing list)
Hi there
how do I pass rails data to a JS array?
like
arr[0] = @user.name
arr[1] = @user.location

something like that
I've been trying differente approaches but no luck so far
thanks in advance
dweinand (Guest)
on 2007-03-09 09:36
(Received via mailing list)
this works for me in rhtml files:
<script type="text/javascript">
  name_id=<%= @name.id %>;
</script>

<script type="text/javascript">
  arr[0] = <%= @user.name %>
</script>

HTH
Eden L. (Guest)
on 2007-03-09 10:16
(Received via mailing list)
to_json is great for this.

var user_obj = <%= @user.to_json %>;

If you want an array of values:

var arr = <%= @user.values.to_json %>;
Jorge Mario G. Mazo (Guest)
on 2007-03-10 02:09
(Received via mailing list)
thanks a lot guys
I tried the to_json but for a lame reasson
it broke the app
webrick wont start
Eden L. (Guest)
on 2007-03-10 05:09
(Received via mailing list)
Weird... can you try: @user.attributes.to_json?

What's in @user?
This topic is locked and can not be replied to.