views:

426

answers:

3

I have a rails form where the end user is going to drop down a list of categories, select a category. I need this selection to update the next select drop down. The issue is that the 2nd select needs to be populated by static data from a partial.

The reason for this, is that its a product registration page, that includes more options than just those living in the db. In fact hardly any of the data is in the db, so it will be easier to just setup 5 lists in partials, that are loaded depending on the category selection.

Just not sure how to set this up. I am using Jquery 1.3.2 and Rails 2.3.3

Any help is greatly appreciated.

A: 

Check out this Railscast on dynamic select menus.

bensie
I checked it out. The issue is that I am not pulling any data from the db. Its all in a few lists. thanks though.
TJ Sherrill
A: 

Check out the ActiveScaffold plugin. It streamlines this process. You want the bit on chaining form fields.

EmFi
A: 

Since you have jQuery as one of your tags I'd go the jQuery route. First select the correct function - if you're just bringing back data then JSON makes the most sense to me. If you want return a list of option tags then a regular get will work.

Here's some pseudo code using get:

$(function() {
  $("#category-select").change(function() {
    var id = $("#category option:selected").val(); // assuming the value is the category id
    var url = "/categories/" + id + "/subcategories/";
    .get(url, function(data) {
      $("#product-select").html(data); // assumes data is a bunch of <option> tags
    });
  });
});
Andy Gaskell
Andy, this is my thought as well from my 2 hours of Googleing. Can you outline in a little more detail. I am going to have a category dropdown and then products in that category as the 2nd. Do I need a Jquery plugin or will just the standard 1.3.2? thanks, this is helping.
TJ Sherrill
You don't need a plugin. If your controller and partial are setup correctly the jQuery code I posted will be *very* close to what you can actually use. Getting AJAX setup with jQuery and Rails takes a few steps. While this blog post doesn't cover your specific scenario it does cover the basics of AJAX with jQuery and Rails. http://gaskell.org/unobtrusive-deleting-with-rails-and-jquery/ If you understand most of what's going on in that post, it's really just setting up your partial and calling the proper URL from your JavaScript.
Andy Gaskell
I am still a newb at Rails. Learning fast but not fast enough. I don't currently have the controller or partials setup. Can you give me some direction on that? If possible don't write the code out, just point me in the right direction. Working through it is the fastest way for me to learn it. Thanks man...
TJ Sherrill