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

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
17d01ff4326c26911481c7a77283b343?d=identicon&s=25 Eric Sloane (Guest)
on 2005-12-16 02:05
(Received via mailing list)
Hi,
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,
Eric
2dd904ec5981c31e7bb7a5743a53caf8?d=identicon&s=25 Bruce Balmer (brucebalmer)
on 2005-12-16 07:24
(Received via mailing list)
Eric:

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
friend).

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
round-tripping.

bruce
C618e1d9ffa1bd1a6b6edc8ad4edec63?d=identicon&s=25 Robert (Guest)
on 2005-12-16 14: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
     end

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

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.