matthewalexander matthewalexander - 3 months ago 7x
Ajax Question

Rails 4, loading api response in memory for drop down select?

Basically I want to pull a list of team objects from an API - the team_id and the team_name is what I'm interested in - as it will allow me to make pertitent API calls later on and to populate a drop down list with options. I want to have the list of 'team names' available in a drop down list, inside of a form used to create a carpool object in my application.

So Far I have this:

carpool_controller.rb (carpools#ts_add_teams_to_memory) controller action being called:

def ts_add_teams_to_memory
ts_teams = current_user.ts_add_teams_to_memory

Where, ts_teams is an array of hashes containing keys [:name] and [:id].

  • grabs teams from the api

  • pulls out attributes 'name' and 'id'

  • creates a hash for each object

  • passes that hash into an array.

  • ts_teams represents that array of hashes.


Here is the form I want to pass the array of hashes into via ajax.

<%= form_for @carpool do |f| %>
<h3>Select Team</h3>
<div class="form-group">
<%= f.collection_select :team_id, #INSERT ARRAY OF HASHES VIA AJAX?, :id, :name, include_blank: true %>
<%= f.submit 'Create Carpool', :class => 'button left' %>
<% end %>

Here is the link I am using to send the ajax request to the correct path:

<%= link_to "Get Teams", ts_add_teams_to_memory_path(,
remote: true,
method: :get,
class: "btn btn-success left",
data: {toggle: "modal", target: "#ts_loading"} %>

How do I push the array of hashes into the collection_select tag in the carpool create form? Or, is there a better way to do this? I need to see the list of team options returned from the API on the page, ideally without reloading the page...

Any help appreciated!


You will need to write some javascript code to do that.

To do it yourself in coffeescript, it will be something like that:

$('#ajax-id').on 'ajax:success', (data) ->
  data.teams.forEach (team) ->
    $('#select-id').append("<option value=#{}>#{name}</option>")

Change the #xxx-ids to the ajax form and select element IDs respectively.

I recommend trying one of the following javascript libraries to make your life a whole lot easier:

They both have remote data support using AJAX.