Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

BJ Keeton
BJ Keeton
5,609 Points

How do I use AJAX to Query a Rails Database to Populate a Div based on a collection_select form?

I have two models:

class Event < ApplicationRecord
has_many :event_options

class EventOption < ApplicationRecord
belongs_to :event

I have this dropdown select_tag:

  <% options = options_for_select(@events.map{ |event| [event.name, event.id] }) %>
  <%= select_tag('event-select', options, prompt: "Please select an event:", class: "form-control") %>

And I use this JavaScript to extract the :event_id and pass it to an AJAX call that, in theory, populates a div with :description and :price params from the EventOption model.

// grab event_id from event-select dropdown
$('#event-select').change(function(e) {
  var event_id = $(this).val();
  console.log(event_id)


// ajax call to populate div with :description and :price


$.ajax({url: '/events/' + event_id,
      type: 'GET',
      success: function(data) {
        $('#event-options').empty().append(data);
        }
     });
 });

Right now, it populates the div with my show.html.erb, but I can't get it to query the database at all or see the :event_id I need it to because I haven't been able to figure out what I need to put in my routes.rb and my EventsController to get the DB query and resulting AJAX call to work.

I feel like I'm close to solving it, but I've been stuck on this for a week, and I'm ready to pull my hair out. Thanks in advance!