max pleaner
max pleaner

Reputation: 26768

Rails: how to pass data from Ruby to Javascript

I am using Rails 4. In one of my controllers, I make a call using HTTParty to get data from the last_fm API - The user specifies a city, and then I have constructed an html page so that the details of upcoming concerts in that city are displayed in a table (title, date, artists, etc).

The next goal of my app is to map these concerts using the Google Maps API. I have managed to load up a map on the page and have the "city" parameter (specified by the user's search) be the location that the map automatically centers at.

Since I got the Last_fm data through a Ruby HTTP method, I had to pass it to the Javascript map API code by using jQuery selectors to snatch up data from the html page. Essentially, in order to pass any data from Ruby (including parameters submitted by the user through forms and the last_fm API request/response), I need to put that code in the html (the 'view') and then use jQuery to get that data into javascript. I was fine using this method, but when I tried to write a function for passing more complex code from Ruby to Javascript, I hit a roadblock.

Here is where I am stuck: There is a line in my javascript file =: console.log($("div.music_id")); I also tried console.log($("div.music_id").contents()); Both simply printed to the console [object Object]. I am not sure why this is the case. I have many div.music_id elements on the page and I need to iterate through them in order to capture information from their child DOM nodes. I am not able to iterate through them because jQuery does not appear to be capturing the element as I hoped it would. I was hoping that it would produce an array of objects that I could then perform further jQuery selector methods on to refine my selection, but I am unable to do this. Thanks for your help. By the way, the code in my 'view' is here (note that it has embedded ruby):

<h1>Show data for city specified on previous page</h1>
  <% @events.each do |x| %>
  <div class="music_id" id=<%= x["id"] %>>
    <div class="venue">
      <h3>Event Venue:</h3>
      <p><%= x["venue"]["name"] %></p>
    </div>
    <div class="time">
      <h3>Date & Time:</h3>
      <p> <%= x["startDate"] %></p>
    </div>
    <div class="event_title">
      <h3>Title:</h3>
      <p> <%= x["title"] %></p>
    </div>
    <div class="artists_playing">
      <h3>Artists playing:</h3>
      <% array = Array(x["artists"]["artist"]) %>
      <% array.each do |y| %>
        <%= array.index(y) + 1 %>)
        <%= y %>
        <br>
      <% end %>
    </div>
    <hr> 
  </div>
<% end %>

and @events refers to this code found in the controller (Ruby code):

@event_list = self.class.get('http://ws.audioscrobbler.com/2.0/', :query => {

:method => 'geo.getEvents',
:location => params[:city],
:format => 'json',
:api_key => 'xxxxxxyyyyyyzzzzz'})
@events = @event_list["events"]["event"]

This Ruby code inherits methods from HTTParty, which I require at the top of the controller. The view code presents the data fine, so the problem is that I unable to move it to the Javascript file.

I am hoping for some advice regarding if there is a better way to pass info from Ruby to Javascript, or how I should do it. Thanks

Upvotes: 1

Views: 4265

Answers (2)

Norly Canarias
Norly Canarias

Reputation: 1736

Try using the gon gem. Ryan bates shows how to use this and gives other options on passing ruby objects to javascript:

http://railscasts.com/episodes/324-passing-data-to-javascript

By the way, have you tried to use inspect element to make sure that the ids inserted to the elements are correct?

Upvotes: 3

Vadorequest
Vadorequest

Reputation: 17997

I think your problem is that you should use json with arrays. Try to use array.to_json. How can I use JavaScript to parse Ruby JSON string

Once converted to json, it should be iterable.

Upvotes: 3

Related Questions