Forum: Ruby on Rails HOW DO I populate options from previous option click

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Eric S. (Guest)
on 2005-12-16 03:05
(Received via mailing list)
I have a form with three drop down option lists. Currently each of these
  contain full listings as instantiated in the controller on entering
the edit action. What I would like to do is filter the second list based
on what the user selected on the first and the third filtered to reflect
the second.
For example I have major_role, role and person_in_role = role is a
subset of major_role and person_in_role is one qualified to act in role
Kind Regards,
Bruce B. (Guest)
on 2005-12-16 08:24
(Received via mailing list)

I figure that even if my answer is semi useless, it is still better
than no answer.  I hope you agree.  And with that out the way, here
is the help I can offer.

It seems to me that there are three ways to achieve the effect you want.

1.  A round trip to the server. That would be easy, so I doubt that
is what you want.

2. Some hideously complex javascript stuff that I still have
nightmares about since I last had to do something like this.  (I
believe debugging javascript has improved since then, firefox is your

3.	Some wonderful ajax stuff.  Sadly, this is where I become
completely useless to you since I have been focusing on other aspects
of rails thus far.  From what I have read and seen, ajax is going to
be nicer to you than doing javascript and nicer to the customers than

Robert (Guest)
on 2005-12-16 15:02
(Received via mailing list)
Change this according to your own needs:

1) View:

<%= select_tag('search[category]', SELECT OPTIONS HERE) %>
<div id="sub_category_wrapper"></div>

<%= observe_field 'search[category]', :url => {:action =>
'search_sub_category_xhr'}, :update => 'sub_category_wrapper', :with
=> "'category_id=' + escape(value)", :complete => visual_effect
(:highlight, 'sub_category_wrapper') %>

2) Now create a new action "search_sub_category_xhr"

   def search_sub_category_xhr
     if params[:category_id] =~ /^[0-9]+$/
       @sub_categories = Category.find(params[:category_id]).children
       render :action => 'search_sub_category_xhr', :layout => false

     if @sub_categories.empty?
       render :nothing => true

3) View for "search_sub_category_xhr"

<%= select_tag 'search[sub_category]',
options_from_collection_for_select(@sub_categories, 'id', 'name') %>
This topic is locked and can not be replied to.