views:

106

answers:

1

Hi,

I currently have two Ruby selects: one for categories and the other one for subcategories. As you may anticipate, the second one has to update itself every time the first one changes.

For example, if I select from the first one the category "Sports", the second select should load all the sports.

How can I handle that "index change" event? Is there a "ruby way" or I have to use javascript?

Thanks, Brian

+2  A: 

You have to use at least some JavaScript. In jQuery, you can do this:

$(document).ready(function(){
    $('#first-select').change(function(){
          $('#second-select').load('/categories/2');
    });
});

In your CategoriesController, your show action should respond to format.js, which should render a subcategories partial:

class CategoriesController
...
def show
  @subcats = SubCategory.find_all_by_parent_category(params[:id])
  ...
  respond_to |format|
    ...
    format.js { render :partial => "subcategories", :locals => { :subcats => @subcats } }
  end
end

and your subcategories partial:

<% subcats.each do |subcat| %>
<option value="<%= subcat.value %>"><%= subcat.text %></option>
<% end %>
Martin Gordon
Thanks. I'll try it.
Brian Roisentul
Question: I'm doing this when I create an announcement, so..should I place the controller code at the Show or at the New method?
Brian Roisentul
You would want it in your category's show method since you are getting data related to one of your categories (not creating a new one).
Martin Gordon
Right. But I don't have a category entity. I just have the categories table at the database. I don't need a controller or a model for them right now. So, I'll see where I can place that login. Thanks a lot.
Brian Roisentul